1

I am working on making a program for making lists but having trouble adding anything that is more than one word. (i.e. pop rocks, or toilet paper)

cout<<"What would you like to add?"<<endl;
    string NewItem;
    cin>>NewItem;

Right now I'm using cin but I saw something about getline() though nothing about if it would help me. When I tried it all I got was a runtime error so I'm not really sure what went wrong.

getline(cin, NewItem);

That is what I replaced the cin with when I tried it. Run time error didn't look for user input it just paused for a second.

  • Yes, `getline()` will certainly help you. Which runtime error message did you get? – Greg Hewgill Apr 21 '15 at 02:36
  • Possible duplicate - http://stackoverflow.com/questions/5838711/c-cin-input-with-spaces – mbsingh Apr 21 '15 at 02:37
  • It just ignored it completely. Like there was nothing there. – HeroftheKnight Apr 21 '15 at 02:40
  • Without seeing the rest of your code, all we can do is guess. I guess that you are mixing the use of `cin >>` and `getline()`, (specifically using `cin >>` in some code before that which you have shown), which almost always doesn't do what you expect. I suggest changing all use of `cin >>` to `getline()` which will behave much more intuitively. – Greg Hewgill Apr 21 '15 at 02:49

2 Answers2

1

You shouldn't mix getline and cin >> (or, if use, use with care, as cin leaves whitespaces in the buffer that may end up "eaten" by getline, so you must ignore them). Use only getline, like

#include <iostream>

using namespace std;

int main()
{
    cout << "What would you like to add?" << endl;
    string NewItem;
    getline(cin, NewItem);

    std::cout << "You added: " << NewItem << std::endl;
}
vsoftco
  • 55,410
  • 12
  • 139
  • 252
0

std::cin extract data to string variable until it see delimiter character in stream. New line and space are delimiters to this function. That is the reason you can't read the string like " pop rocks" completely. It will read up to first space and stop reading from stream.

Steephen
  • 14,645
  • 7
  • 40
  • 47