首页 文章

我怎样才能确切地看到std :: cin输入缓冲区中的内容?

提问于
浏览
0

我遇到的问题是,当一个人在控制台中键入内容时,我想要确切地看到输入缓冲区中的内容我知道如何查看它的唯一方法是使用std :: cin :: getline()或std: :getline(),但我认为这两个都写入char指针或std :: string对象,具体取决于系统特定的行尾字符是否合适 . 例如,我认为在Windows上如果你在控制台上按Enter键它会输入'\ r''\ n',但是当我尝试从char指针或字符串对象中读取它时它们不显示任何'' R” . 例如,如果我在控制台中键入单词hello,我怀疑windows放置:

'h''e''l''''o''\ r''\ n'

进入缓冲区,但在char指针或字符串对象中我只看到“你好” . 我基本上想要看看输入缓冲区中的内容 . 我可以在一个循环中逐个从缓冲区中提取每个字符,而不会抛出空格字符吗?

2 回答

  • 2

    std::cinstd::basic_istream,可以这样操作 .

    通常,您可以使用>>getline来读取流 . 这两个都是"know when to stop" .

    但是如果你想用 \n 来查看缓冲区,那么假定你将使用换行符字符从控制台传递流,并且你用来读取它的函数不会是换行符 .

    你可以copy the buffer to a string . 但请记住,你必须以其他方式signal the EOF .

    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main() {
        std::ostringstream oss{};
        oss << std::cin.rdbuf();
        std::string all_chars{oss.str()};
        std::cout << all_chars;
        return 0;
    }
    

    在Windows上,如果我键入helloEnterthereEnter后跟Ctl z(必须在Windows的新行上),那么我看到:

    hello
    there
    ^Z
    hello
    there
    

    因此,在此示例中,包括换行符在内的所有内容都存储在 std::string 中 .


    但我只看到\ n的行结尾 . 我认为Windows应该使用\ r \ n进行行结尾

    我添加了以下内容以明确显示各个字符:

    int index{};
    for(auto mychar : all_chars)
        std::cout << std::setw(3) << index++ << ": character number " << std::setw(5) << static_cast<int>(mychar) 
            << " which is character\t"<< ((mychar == 10) ? "\\n" : std::string{}+mychar) << '\n';
    

    对于相同的输入,它产生:

    hello
    there
    ^Z
    hello
    there
      0: character number   104 which is character  h
      1: character number   101 which is character  e
      2: character number   108 which is character  l
      3: character number   108 which is character  l
      4: character number   111 which is character  o
      5: character number    10 which is character  \n
      6: character number   116 which is character  t
      7: character number   104 which is character  h
      8: character number   101 which is character  e
      9: character number   114 which is character  r
     10: character number   101 which is character  e
     11: character number    10 which is character  \n
    

    所以这表明只有 \n 从控制台传递,没有找到 \r . 我使用Windows 10进行此测试,但我认为这已经有一段时间了 .

  • 0

    我认为这应该有效:

    std::string mystring;
    std::cin >> mystring;
    
    for(unsigned int i = 0; i < mystring.size(); i++)
    {
        switch(mystring[i])
        {
            case ‘\n’:
                cout << “\\n”; // print \n by escaping the slash
                break;
            case ‘\r’:
                cout << “\\r”; // print \r by escaping the slash
                break;
            // OTHER CASES HERE
            default:
                cout << mystring[i]; // print the string normally
                break;
        }
    }
    

相关问题