奇怪的 c++输入转义和空间行为
我的 c++ 示例遇到了一个令人不快的问题。一切正常,直到我输入带有空格的内容。
#include <iostream>
using namespace std;
int main (int argc, char * const argv[])
{
int iteration = 0;
while (true) {
char * input = new char[256];
scanf("%s", input);
cout << ++iteration << ": " << input << endl;
cin.get();
}
return 0;
}
因此,使用这段代码,我可以输入任何内容,但是空格之后的所有内容都以某种方式存储在缓冲区中并在第二次迭代中使用。
foo
1: foo
bar
2: bar
foobar
3: foobar
foo bar
4: foo
5: bar
每个输入读取功能都是这样的,这让我发疯。 cin>> input
、freads()
、cin.get()
等都执行此操作。
这是用户输入的常见问题,还是我在这里做错了什么?
I'm having an unpleasant problem with my c++ example. Everything works fine until I enter something with a whitespace.
#include <iostream>
using namespace std;
int main (int argc, char * const argv[])
{
int iteration = 0;
while (true) {
char * input = new char[256];
scanf("%s", input);
cout << ++iteration << ": " << input << endl;
cin.get();
}
return 0;
}
So with this code, I can enter anything, but everything after whitespace is somehow like stored in buffer and used in the second iteration.
foo
1: foo
bar
2: bar
foobar
3: foobar
foo bar
4: foo
5: bar
Every single input reading function acts like this and it's driving me crazy. cin >> input
, freads()
, cin.get()
etc. all do this.
It this frequent problem with user input, or am I doing something wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,永远不要使用
scanf
。很难使用该函数并避免缓冲区溢出。将input
替换为std::string
,并从std::cin
读取。scanf("%s", input)
和cin >> input
将读取一个单词,以空格分隔。如果您想读取整行,请使用getline(cin, input)
。First of all, never use
scanf
. It's difficult to use that function and avoid buffer overflows. Replaceinput
with astd::string
, and read fromstd::cin
.Both
scanf("%s", input)
andcin >> input
will read one word, delimited by whitespace. If you want to read a whole line, then usegetline(cin, input)
.关于
scanf %s
格式说明符:关于
istream::operator>>
与 str参数:所以是的,这是这些函数的标准行为。
About
scanf %s
format specifier:About
istream::operator>>
with str parameter:So yes, this is standard behaviour for these functions.
也许尝试使用 std::getline 代替?
http://www.cplusplus.com/reference/string/getline/
Maybe try using std::getline instead?
http://www.cplusplus.com/reference/string/getline/