std::cin skips white spaces

雨燕双飞 提交于 2019-12-04 06:46:22

Ok, I'll try to explain your problem:

Let's assume this is your input:

thisisaword
this is a sentence

When you use cin and give it any input, it stops at the newline character which in my example follows character 'd' in 'thisisaword'.
Now, your getline function will read every character until it stops newline character.
Problem is, the first character getline encounters is already a newline so it stops immediately.

How is this happening?

I'll try to explain it like this:

If this is your input given to a program (note \n characters, treat it like a single character):

thisisaword\n
this is a sentence\n

What your cin function will take and leave:

\n
this is a sentence\n

Now getline sees this input and is instructed to get every character until it meets a newline character which is "\n"

\n <- Uh oh, thats the first character it encounters!
this is a sentence\n

cin reads input and leaves "\n", where getline includes "\n".

To overcome this:

\n <- we need to get rid of this so getline can work
this is a sentence\n

As said, we cannot use cin again because it will do nothing. We can either use cin.ignore() without any parameters and let it delete first character from input or use 2x getline(first will take remaining \n, second will take the sentence with \n)

You can also avoid this kind of problem switching your cin >> Word; to a getline function.

Since this is tagged as C++ I changed Char*[] to Strings for this example:

string Word, Sentence;

cout << "Please enter a word: "; cin >> Word;
cout << endl << Word;

cin.ignore();

cout << "\nPlease enter a sentence: "; getline(cin, Sentence); 
cout << endl << Sentence;

OR

string Word, Sentence;

cout << "Please enter a word: "; getline(cin, Word); 
cout << endl << Word;

cout << "\nPlease enter a sentence: "; getline(cin, Sentence); 
cout << endl << Sentence;

How about using this:

std::cin >> std::noskipws >> a >> b >> c;

cin by default utilizes something like this:

std::cin >> std::skipws >> a >> b >> c;

And you can combine flags:

std::cin >> std::skipws >> a >> std::noskipws >> b;

Tell me if it works for you : )

By default operator>> skips whitespaces. You can modify that behavior.

is.unsetf(ios_base::skipws)

will cause is's >> operator to treat whitespace characters as ordinary characters.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!