据我所知,提取操作符会跳过开头的空格,并在遇到空格或流结尾时停止.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<<"
";
cout<<"Enter another name ";
cin>>name;
cout<<"You entered "<<(int)name[0]<<"
";
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
谢谢!!!
>>
字符串的基本算法是:
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
.在这种情况下,流 always 提取一个字符.)
>>
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的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!