2013-02-15 37 views
1

中刪除字符串我正在嘗試將多個值讀入到我的C++程序中。C++ Integer從* char []

當我輸入1位數字(在我的代碼的底部),我很好。

但是,如果輸入2位數字,如「10」,則消息(我輸入的第二個東西)將被刪除。

這裏是我的代碼:

char * args[6]; 
unsigned time = 5; 
char input[5]; // for string input 
string message= "message"; 
//these strings and *chars are tempary strings for the purpose of reading in data 
string temp; 
char *temp2 = " "; 
char *temp3 = "empty pointer"; 

    args[count] = "-m"; 
    count ++; 

    //Prompt for the message 
    cout <<endl<<"Alright, Please enter your message: "<<flush; 
    getline(cin, message); 
    cout <<endl<<endl; 
    message.append("\""); 
    message = "\""+message; 
    //we can't use the string, so we copy it to temp3. 
    strcpy(temp3, message.c_str()); 
    //Now we input the string into our array of arguments 
    args[count] = temp3; 
    count ++; 


    cout <<"Please enter time "<<flush; 
    getline(cin,temp); 

    //validate input utnil its an actual second. 
    bool done = false; 
    while (done == false){ 
     for(unsigned i = 0; i < temp.length() & i < 5; i++){ 
      input[i] = temp[i]; 
     } 
    done = CheckInteger(input, input); 
     time = atoi(input); 
     if (done == true & time < 1) { 
      cout <<"Unable to use a number less than 1 seconds! "<<endl; 
      cout <<"Please enter the number of seconds? "<<flush; 
      done = false; 
     }else if (done == false){ 
      cout <<"Please enter the number of seconds? "<<flush; 
     }else{ 
     break; 
     } 
     getline(cin,temp); 
    } 
    cout <<endl<<endl; 
    time = atoi(input); 
    //timer argument 
    args[count] = "-t"; 
    count ++; 

    // enter the time need to comvert from int to string. 
    ostringstream convert; 
    convert <<time; 
    temp = convert.str(); 
    //need to convert from string to character 
    strcpy(temp2, temp.c_str()); 

    args[count] = temp2; 
    count ++; 

我怎樣才能解決這個問題?

+0

「'//我們不能使用字符串,所以我們把它複製到temp3.'」? ***爲什麼***不能使用'string'? – Johnsyweb 2013-02-15 21:50:36

+0

你爲什麼要兩次輸入? '完成= CheckInteger(輸入,輸入);'這個函數做什麼? – corn3lius 2013-02-15 21:52:07

+0

我不使用字符串,因爲當我使用字符串時,最終得到了一個進程轉儲。另外,我將兩個輸入傳入兩次,int CheckInteger,因爲一個是指針,另一個不是。我知道這不是最有效的方法,但它做我需要做的。 – user1797035 2013-02-15 22:02:22

回答

4

strcpy(char* destination, const char* source)source字符串複製到destination指向的數組中。但是,你在呼喚strcpy(temp3, message.c_str());試圖將字符串複製到指針常量字符串文字:char *temp3 = "empty pointer";,從而導致未定義行爲 [1]

變化temp3從指針到將與此字符串只是初始化數組字面:

char temp3[] = "empty pointer"; 

或甚至更好:使用std::string來代替。


[1] C++ 03標準2.13.4字符串文字(選定部分)

§1一個普通字符串文字已鍵入「的N陣列const char「和靜態存儲時間

§2試圖修改字符串文字是未定義的。

+0

謝謝。這是導致問題的指針。我將它改爲char temp3 []; – user1797035 2013-02-15 21:58:58

+0

@ user1797035:不客氣:) – LihO 2013-02-15 22:06:51

+1

@ user1797035:這是一個壞主意。如果用戶輸入的消息比「空指針」長,那麼你會溢出緩衝區並破壞你的堆棧。整個函數可以並且應該使用'std :: string'來實現。 [Q.E.D.](http://ideone.com/KV5DL6) – Johnsyweb 2013-02-15 23:24:26