everyone. I am an experienced C programmer trying to get adjusted to C++. I would like to do the equivalent of this C statement...
sscanf(str, "%s %s", sub1, sub2);
...but with C++'s string object. Say str is "hello world", doing the above sscanf statement would put "hello" in sub1, and "world" in sub2. I know I can use C functions like that in C++, but I would like to use the C++ string object instead of an array of chars. I've tried this:
string q, h, w;
cout << "Type \"hello world\": ";
cin >> q;
istringstream x(q);
x >> h >> w;
if (h == "hello")
cout << "Yes!\n";
else
cout << "No!\n";
if (w == "world")
cout << "Yes!\n";
else
cout << "No!\n";
But it outputs "Yes! No!", which means it picked up the "hello" but not the "world". Any ideas?
That is because the operator>>
used with cin
will only capture the "hello" phrase, and will stop at the first delimiter (in this case a space). If you want to capture the entire input line up to the first line-delimiter typed by the user, you will have to use getline(cin, q)
. The two-argument version of getline()
uses a newline as the delimiter, but there is a three-argument version that allows you to specify a custom line-delimiter character as well.