noskipws对cin>的影响> [英] Effect of noskipws on cin>>
问题描述
根据我的理解,提取操作符在开始时跳过空格,并在遇到空格或字符串结尾时停止。 noskipws可以用来停止忽略前面的空格。
As I understand, the extraction operator skips the whitespace in the beginning and stops upon encountering a whitespace or end of stream. noskipws can be used to stop ignoring the leading whitespaces.
我有以下程序,我使用noskipws。
I have the following program where I have used noskipws.
#include <iostream>
using namespace std;
int main()
{
char name[128];
cout<<"Enter a name ";
cin>>noskipws>>name;
cout<<"You entered "<<name<<"\n";
cout<<"Enter another name ";
cin>>name;
cout<<"You entered "<<(int)name[0]<<"\n";
return 0;
}
我的查询是:
-
如果我输入John作为第一个输入,则第二个cin >>操作不等待输入,也不会将任何东西复制到目标,即名称数组。我期望第二个cin >>到至少一个换行或流结束,而不只是设置目标字符串为空。为什么会发生这种情况?
If I enter "John" as the first input, then the second cin>> operation does not wait for input and does not copy anything to the destination i.e. the name array. I expected second cin>> to transfer at-least a newline or end of stream, instead of just setting the destination string to empty. Why is this happening ?
当我输入John Smith作为第一个cin >>语句的输入时,观察到同样的情况。为什么第二个cin >>语句不会将空格或Smith复制到目标变量?
The same thing is observed when I enter "John Smith" as the input for first cin>> statement. Why doesn't the second cin>> statement copy the space or "Smith" to the destination variable ?
以下是程序的输出:
Enter a name John
You entered John
Enter another name You entered 0
Enter a name John Smith
You entered John
Enter another name You entered 0
>
推荐答案
字符串>>
的基本算法是: p>
The basic algorithm for >>
of a string is:
skip whitespace
read and extract until next whitespace
如果使用 noskipws
,则跳过第一步。第一次读取后,您位于空白处,因此下一个(以及所有后续的)读取将立即停止,不提取任何内容。
If you use noskipws
, then the first step is skipped. After the first read, you are positionned on a whitespace, so the next (and all following) reads will stop immediatly, extracting nothing.
;>
到字符串将永远不会将空格放入字符串。更一般地,使用>> 与
noskipws
有问题,因为空格总是>>
;它可能有意义的使用它准时,但它通常应该在使用后立即重置。 (在使用>>
到 char
时可能有意义的一次性情况在这种情况下, 提取一个字符。)
>>
to a string will never put whitespace into the string. More generally, using >>
with noskipws
is problematic, since whitespace is always a separator for >>
; it may make sense to use it punctually, but it should generally be reset immediately after it has been used. (The once case where it might make sense is when using >>
to a char
. In this case, the stream always extracts one character.)
这篇关于noskipws对cin>的影响>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!