1

C++ プログラムにいくつかの値を読み込もうとしています。

(コードの一番下に) 1 桁の数字を入力すると、問題ありません。

ただし、「10」などの 2 桁の数字を入力すると、メッセージ (2 番目に入力したもの) が消去されます。

これが私のコードです:

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 ++;

どうすればこれを修正できますか?

4

1 に答える 1

4

strcpy(char* destination, const char* source)source文字列を。が指す配列にコピーしますdestinationstrcpy(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文字列リテラルを変更しようとした場合の影響は定義されていません。

于 2013-02-15T21:54:12.490 に答える