C ++ Integer从* char []中删除字符串

时间:2013-02-15 21:49:01

标签: c++ string pointers int string-literals

我正在尝试将几个值读入我的C ++程序。

当我输入一位数字(在我的代码底部)我很好。

但是,如果我输入一个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 ++;

我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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尝试修改字符串文字的效果未定义。