-1

I just started an entry level C++ class and I am doing my first homework assignment. The code seems to work perfectly fine except for when the input includes a space in it, then it just skips over the rest of the questions of after the line the input was on.

I hope this makes sense!

// This program prompts the user a few general questions about themselves, the date, which IDE they are using, and which machine they have downloaded the IDE on to.


#include <iostream>
#include <string>
using namespace std;

int main()
{
    string userName, currentDate, softwareName, machineName;

    //Ask the user his name.
    cout << "What is your name? ";
    cin >> userName;

    //Ask the user the date.
    cout << "What is the date? ";
    cin >> currentDate;

    //Asks the user which software he downloaded.
    cout << "What is the name the IDE software you downloaded? ";
    cin >> softwareName;

    //Asks the user which machine he downloaded his IDE on.
    cout << "Which machine did you download the IDE on? (ie. home computer, laptop, etc.) ";
    cin >> machineName;

    //Prints out the users inputs going downwards.
    cout << "" <<  userName << endl;
    cout << "" <<  currentDate << endl;
    cout << "" <<  softwareName << endl;
    cout << "" <<  machineName << endl;
    return 0;
}

1 Answers1

0

The extraction operator (>>) will read the input until either a space or a next line (and probably other whitespace characters but I'm not sure). So when you type in something with spaces, the part after the space is interpreted as the answer for the next question. To read input with spaces, use the getline() function which won't stop reading at spaces by default like this: getline(cin, userName). Note that the extraction operator will leave line breaks in the input stream, which will cause a subsequent getline() call to give an empty string. Make sure to call cin.ignore() before calling getline() after an extraction.

eesiraed
  • 4,626
  • 4
  • 16
  • 34