Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Never use iostreams without error checking. As Jason says, read the whole line, not just one token, but even then do check for errors:

std::string line;

if (std::getline(std::cin, line))
{
    std::string h, w;
    std::istringstream iss(line);

    if (iss >> h >> w)
    {
        // success
    }
    else
    {
        std::cerr << "Error reading your input.\n";
    }
}
else
{
    std::cerr << "Error reading from stdin!\n";
}

You can make the ifs into loops if you want to keep reading.

Basically, you can check every formatted extraction (getline, >>) as a condition, since the result is convertible to something testable, and the condition will be false if the operation failed. Therefore, you must never interpret the purported recipient variables unless the operation succeeded!

Had you added this check to your code x >> h >> w;, you would never have made it past that line without failing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top