-2

about the code below, string doesn't light up anymore and when I entered "John Smith", only "John" appears, string was working fine for me weeks ago until i tried calling strings function today which didn't work so i tested for a simpler one.

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

int main ()
{
    string name;          

   // Get the user's name
   cout << "Please enter your first name: "; 
   cin  >> name;

   // Print the greeting
    cout << "Hello, " << name << "." << endl;

    return 0;
}

string doesn't light up like int

I might be asking at the wrong place but I cant' tell what's the problem, please help :(

yun1001
  • 13
  • 4

3 Answers3

0

With std::string's, using std::cin >> someString will only read the first word off the buffer (it will stop at the first whitespace encountered).

Use getline(std::cin, someString) instead to read the entire line.

TrebledJ
  • 8,713
  • 7
  • 26
  • 48
0

To get all the line, use getline(cin, name);

instead of cin >> name;

See http://www.cplusplus.com/reference/string/string/getline/

user8309168
  • 49
  • 1
  • 2
  • 1
    May I suggest https://en.cppreference.com/w/cpp/string/basic_string/getline as a *better* reference? Cplusplus.com is (IMHO) a very *bad* reference site and not one you should use. Cppreference.com is *much* higher quality. – Jesper Juhl Aug 18 '18 at 15:22
-2

std::cin gets only characters to first 'white' character, like space, tab or enter.

If you want to read whole line use e.g. getline()

string line;
cin.clear(); //to make sure we have no pending characters in input buffer

getline(cin, line);
colorgreen
  • 265
  • 1
  • 2
  • 12
  • While that's true, it's not the question. The question is about why the IDE doesn't display `string` the same way it does `int`. – Pete Becker Aug 18 '18 at 15:01