简体   繁体   English

奇怪的C ++输入转义和空间行为

[英]Weird c++ input escaping and space behavior

I'm having an unpleasant problem with my c++ example. 我的C ++示例遇到了令人不快的问题。 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. cin >> inputfreads()cin.get()等都可以做到这一点。

It this frequent problem with user input, or am I doing something wrong here? 用户输入经常出现问题,还是我在这里做错了?

First of all, never use scanf . 首先,不要使用scanf It's difficult to use that function and avoid buffer overflows. 使用该函数并避免缓冲区溢出很困难。 Replace input with a std::string , and read from std::cin . std::string替换input ,并从std::cin读取。

Both scanf("%s", input) and cin >> input will read one word, delimited by whitespace. scanf("%s", input)cin >> input都将读取一个单词,由空格分隔。 If you want to read a whole line, then use getline(cin, input) . 如果要阅读整行,请使用getline(cin, input)

About scanf %s format specifier : 关于scanf %s格式说明符

This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab). 这将读取后续字符,直到找到空白为止(空白字符被视为空白,换行符和制表符)。

About istream::operator>> with str parameter : 关于带有str参数的istream::operator>>

Extraction ends when the next character is either a valid whitespace or a null character, or if the End-Of-File is reached. 当下一个字符是有效的空格或空字符,或者到达文件末尾时,提取结束。

So yes, this is standard behaviour for these functions. 是的,这是这些功能的标准行为。

Maybe try using std::getline instead? 也许尝试改为使用std :: getline? http://www.cplusplus.com/reference/string/getline/ http://www.cplusplus.com/reference/string/getline/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM