Ignoring spaces with string

Hello there, Sorry if this has been asked before, but I cannot find an answer for this anywhere. I am taking my first C++ class and this problem came up which my professor referred as "Very easy" but I can't seem to figure it out. Also, sorry, I don't have the code with me but I do have pictures on the code I'm working on below.

http://i42.tinypic.com/2wd0xn5.jpg
http://i39.tinypic.com/11vqj5h.jpg
http://i39.tinypic.com/2wbtaon.jpg

My problem lies in the range of the lines 48-52, I am trying to run the program having the string line ignore the spaces, however when I run the program and I ask the user to input a phrase, for example "Hello World", the program will only display "World" This means that the code is discarding everything until the space. I want it to display the whole thing and if I don't apply the cin.ignore(1000, " ") it will freak out.

I'll try to highlight the essential part of code where the problem is.


1
2
3
4
5
6
7
8
9
10
11
12
13
 #Include <iostream>
 #Include <string>
 using namespace std;

int_main()

string s;

cout << "Enter a sentence: ";
getline(cin, s);
cin.ignore(1000, " ");
cin >> s;
cout << s << endl;

Can Someone help me please?
Last edited on
when you have statements such as cin >> x; you need to follow that statement with a call to cin.ignore(); to remove the newline from the input stream.
this statement cin.ignore(1000, " "); is the reason the first word is being ignored.
Yanson wrote:
you need to follow that statement with a call to cin.ignore();
And it would work just brilliant if there is some other junk before newline

Proper way to do this:
1
2
3
#include <limits>
...
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');


Also you need to use ignore between >> and getline operations, not after getline.

And let me introduce you to http://pastebin.com/ — best way to show some code.
Topic archived. No new replies allowed.