Search code examples
c++stringpointersintstring-literals

C++ Integer removes string from *char[]


I'm trying to read in several values into my C++ program.

When I enter in a 1 digit number (at the bottom of my code) I'm fine.

However, if I enter a 2 digit number, like "10", the message (the second thing I enter) becomes erased.

Here is my code:

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

How can I fix this?


Solution

  • strcpy(char* destination, const char* source) copies the source string into the array pointed by destination. But you are calling strcpy(temp3, message.c_str()); that tries to copy the string into the pointer to constant string literal: char *temp3 = "empty pointer";, which leads to undefined behaviour [1]

    Change temp3 from pointer to an array that will be just initialized with this string literal:

    char temp3[] = "empty pointer";
    

    or even better: use std::string instead.


    [1] C++03 Standard 2.13.4 String literals (selected parts):

    §1 An ordinary string literal has type “array of n const char” and static storage duration

    §2 The effect of attempting to modify a string literal is undefined.