Difference between cin and cin.get() for char array

一曲冷凌霜 提交于 2019-11-28 21:36:45
Mike Seymour

They do different things, so choose whichever does what you want, or the better alternatives given below.

The first cin>>a; reads a single word, skipping over any leading space characters, and stopping when it encounters a space character (which includes the end of the line).

The second cin.get(a,256);cin.get(); reads a whole line, then consumes the end-of-line character so that repeating this will read the next line. cin.getline(a,256) is a slightly neater way to do this.

The third cin.get(a,256) reads a whole line but leaves the end-of-line character in the stream, so that repeating this will give no more input.

In each case, you'll get some kind of ill behaviour if the input word/line is longer than the fixed-size buffer. For that reason, you should usually use a friendlier string type:

std::string a;
std::cin >> a;              // single word
std::getline(std::cin, a);  // whole line

The string will grow to accommodate any amount of input.

Nazara

The problem, most likely, is in the way you enter the values later on. The cin.get() after every initialization is there to "grab" the newline character that gets put in the stream every time you press enter. Say you start entering your values like this:

2 

a b c d...

Assuming you have pressed enter after 2, the newline character was also put on the stream. When you call cin.get() after that, it will grab and discard the newline character, allowing the rest of your code to properly get the input.

To answer your first question, for an array, you should use cin.get instead of the overloaded operator >> cin>> as that would only grab a single word, and it would not limit the amount of characters grabbed, which could lead to an overflow and data corruptions / program crashing.

On the other hand, cin.get() allows you to specify the maximum number of characters read, preventing such bugs.

For a char array use cin.get() because it counts whitespace whereas cin does not and more importantly sets the maximum number characters to read for example.

 char foo[25]; //set maximum number of characters 
 cout << "Please type in characters for foo << endl;
 cin.get(foo,25);
 cout << ' ' << foo;

In this case you can only type in 24 characters and a null terminator character '/0'. I hope this answers your first question. I would personally use a string.

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