C++ Part 30

String | Getline and Cin


string s1, s2;
cin >> s1;
cin >> s2;
If the user types in
I love NavidPlus website.
s1 will receive value "I" and s2 will receive the value "love".
If you want your program to read an entire line of input into a variable of type string , you can use the function getline.
Example:
string line;
cout << "Enter a line of input:\n"; getline(cin, line); cout << line << "END OF OUTPUT\n";

I/O with string Objects
You can use the insertion operator << with cout to output string objects. You can input a string with the extraction operator >> and cin.
  • When using >> for input, the code reads in a string delimited with whitespace.
    You can use the function getline to input an entire line of text into a string object.
    EXAMPLES
    string greeting("Hello"), response, nextLine;
    cout << greeting; cin >> response;
    getline(cin, nextLine);
  • Post a Comment

    Popular Posts