user1681673
user1681673

Reputation: 368

Can't assign characters to string variables

I'm trying to break up a user input string into different variables. The exact format of the user string must be "Tuesday 6:40 PM". I written the program so that once the loop hits the first space the rest of the variables will be filled because only the days name will be different lengths. I've tried this a few times and can't seem to get any sort of output.Anyone know why?

void input( Time & time ){
    string inputTime;
    string charholder;
    string day;
    string hour;
    string minute;
    string amPm;

    cout << "Enter a day and time: ";
    getline(cin, inputTime);

    for (int i = 0; i < inputTime.length() ; i++) {

        charholder = inputTime[i];
        cout << i << endl;

        if (charholder != " ") {
            day[i] = inputTime[i];
        }

        else {
            hour[0] = inputTime[i+1];
            minute[0] = inputTime[i+3];
            minute[1] = inputTime[i+4];
            amPm[0] = inputTime[i+6];
            amPm[1] = inputTime[i+7];
            break;
        }
    }

    cout << day << hour << minute << amPm; 
}

EDIT: CORRECT CODE:

void input( Time & time ){
    string inputTime;
    char charholder;
    string day;
    string hour;
    string minute;
    string amPm;

    cout << "Enter a day and time: ";
    getline(cin, inputTime);

    int i = 0;

    while (charholder != ' ') {

        charholder = inputTime[i];
        i++;
    }

    day = inputTime.substr(0,i);
    hour = inputTime.substr(i,1);
    minute = inputTime.substr(i+2,2);
    amPm = inputTime.substr(i+5,2);

    }

Upvotes: 0

Views: 534

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

Assigning a single char to an std::string is OK. But you have many default constructed strings, which you then try to assign elements to using operator[] and an index. But they are all size 0, so these locations are not valid.

std::string foo; // empty string
foo[0] = 'x':    // Oops! foo[0] holds for the null-termination character. Modifying is UB
foo[1] = 'x':    // Oops! foo[1] is out of bounds

Upvotes: 2

Drew Dormann
Drew Dormann

Reputation: 63755

This creates a string with length 0.

string hour;

And this does not change the length of the string.

hour[0] = inputTime[i+1];

If you need the string to be a particular length, call std::string::resize()

Upvotes: 1

Related Questions