代码之家  ›  专栏  ›  技术社区  ›  Mikulas Dite

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

  •  1
  • Mikulas Dite  · 技术社区  · 15 年前

    我的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() 等等,都是这样。

    3 回复  |  直到 15 年前
        1
  •  4
  •   Mike Seymour    15 年前

    首先,不要使用 scanf . 很难使用该函数并避免缓冲区溢出。替换 input 用一个 std::string ,并从 std::cin .

    scanf("%s", input) cin >> input 将读取一个单词,由空格分隔。如果你想读一整行,那就用 getline(cin, input) .

        2
  •  1
  •   Péter Török    15 年前

    关于 scanf %s format specifier :

    关于 istream::operator>> with str parameter :

    当下一个字符是有效的空白或空字符时,或者到达文件结尾时,提取结束。

    是的,这是这些函数的标准行为。

        3
  •  1
  •   Craig Wright    15 年前

    或许可以尝试改用std::getline? http://www.cplusplus.com/reference/string/getline/