2013-02-15 36 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