1

I'm learning about splitting strings for a program in class, and i came across this example.

#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string str = "23454323 ABCD EFGH";

    std::istringstream iss(str);

    std::string word;
    while(iss >> word)
    {
        std::cout << word << '\n';
    }
}

I modified so that the user instead inputs the string,but if I input the string stored in str i get 23454323 and not the other material in the string.

#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
    string str;
    cout<<"Enter a postfix with a space between each object:";
    cin>>str;
    istringstream iss(str);

    string word;
    while(iss >> word)
    {
        cout << word << '\n';
    }
}

Ok, thanks for the help everyone got it!

Ron
  • 21
  • 1
  • 4
  • `std::cin >> str;` acts the exact same way as `iss >> word`. – chris Oct 28 '13 at 18:50
  • I assume this is all related to [the same assignment](http://stackoverflow.com/questions/19641705/how-to-push-a-string-into-a-stack-one-element-at-at-time). – WhozCraig Oct 28 '13 at 18:51
  • `cin >> str` will read up to first whitespace, and "eat" that whitespace. So, you're giving the algorithm much different input in the second case. Running through each line in a debugger would help. So would reading about each method you are using in a C++ API reference. –  Oct 28 '13 at 18:54

3 Answers3

2

You need to modify your input code a little for this to work. Use:

getline(cin, str);

instead of:

cin >> str;

The latter will stop reading a string on whitespace characters.

pippin1289
  • 4,861
  • 2
  • 22
  • 37
0

Because you use the same input operator as for istringstream when you input from cin and it always breaks on whitespace.

That means you only read a single word from the user. You want to use std::getline.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Just as iss >> word reads a single space-separated word from iss, so cin >> str just reads the first word from cin.

To read a whole line, use getline(cin, str).

(Also, get out of the habit of dumping namespace std into the global namespace. It will cause problems as your programs grow.)

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644