【发布时间】:2012-06-12 09:22:20
【问题描述】:
据我了解,提取运算符会在开头跳过空格,并在遇到空格或流结尾时停止。 noskipws 可用于停止忽略前导空格。
我有以下使用 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>> 至少传输一个换行符或流的结尾,而不是仅仅将目标字符串设置为空。为什么会这样?
当我输入“John Smith”作为第一个 cin>> 语句的输入时,会观察到同样的情况。为什么第二个 cin>> 语句不将空格或“Smith”复制到目标变量?
以下是程序的输出:
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
谢谢!!!
【问题讨论】:
-
我希望你知道你的程序很容易产生缓冲区溢出。在生产代码中,您不应使用
std::cin写入字符数组。请改用std::string。 -
确实如此。上述代码仅用于说明目的。使用 cin.width 或 cin.getline 可以避免一些溢出问题,但正如你提到的 std::string 最好。我给出上面的示例代码只是为了展示我想要问的内容。
标签: c++ stream manipulators