【问题标题】:Reading one word at a time from input stream into char array?一次从输入流中读取一个单词到 char 数组中?
【发布时间】:2014-12-20 18:55:17
【问题描述】:

我正在尝试让我的程序一次读取一个单词,直到检测到“完成”一词。但是,我似乎无法正确使用语法,首先如您所见,我使用了读取整行的 getline 函数。但这不是我理想中想要的,所以我决定尝试使用 cin.get 因为我知道它只会读取输入,直到遇到空格或 \n。可悲的是,一次遍历后失败,使我能够输入任何内容...以下是我的源代码。

我的源代码:

#include <iostream>
#include <cstring>

int main()
{
    char ch[256];
    std::cout << "Enter words\n";
    std::cin.get(ch, 256);
    while(strcmp(ch, "done")!=0)
    {
        std::cin.getline(ch, 256); // this reads the entire input, not what I want
        // std::cin.get(ch, 256); this line doesn't work, fails after one traversal

    }
    return 0;

} 

示例运行:

用户输入:你好,我的名字完成了

然后我的程序会一次将每个单词读入 char 数组,然后我在 while 循环中的测试条件检查它是否有效。

到目前为止,这不起作用,因为我正在使用 getline,它读取整个字符串,并且只有在我自己键入字符串“done”时它才会停止..

【问题讨论】:

  • 为什么不使用 std::string 而不是 char 数组?然后做cin &gt;&gt; word
  • 如果你要使用 C++,那就用它吧。'
  • 我的教科书 C++ Primer Plus 说我必须使用 char 数组..
  • 那是一本糟糕的教科书。
  • @AlanStokes 也许这是一个了解正在发生什么的练习?

标签: c++


【解决方案1】:

std::istream::getline()std::istream::get()char 数组版本)之间的区别在于后者不提取终止字符而前者提取。如果您想读取格式化并在第一个空格处停止,您可以使用输入运算符。将输入运算符与 char 数组一起使用时,请确保设置数组的宽度,否则会为程序创建潜在的溢出(和攻击向量):

char buffer[Size]; // use some suitable buffer size Size
if (std::cin >> std::setw(sizeof(buffer)) >> buffer) {
    // do something with the buffer
}

请注意,此输入运算符在到达空格或缓冲区已满时停止读取(其中一个 char 用于空终止符)。也就是说,如果您的缓冲区对于一个单词来说太小并且它以"done" 结尾,那么您最终可能会检测到结尾字符串,尽管它实际上并不存在。使用std::string更方便:

std::string buffer;
if (std::cin >> buffer) {
    // do something with the buffer
}

【讨论】:

    【解决方案2】:
    #include <iostream>
    #include <string>
    
    int main()
    {
        char ch[256];
        std::cout << "Enter words\n";
        std::cin.get(ch, 256);
        std::string cont;
    
        while (cont.find("done") == std::string::npos)
        {
            cont = ch;
    
            std::cin.getline(ch, 256); // this reads the entire input
    
    
        }
    
    
    
    
        return 0;
    }
    

    使用字符串更容易!

    http://www.cplusplus.com/reference/string/string/find/

    【讨论】:

    • 您的代码省略了 OP 希望在处理完第一行后输入另一行的情况。
    • 对不起,这应该可以解决它.. 看看下面
    【解决方案3】:
    #include <iostream>
    #include <string>
    
    int main()
    {
        char ch[256];
        std::cout << "Enter words\n";
    
        std::string cont;
    
        while (cont.find("done") == std::string::npos)
        {
    
    
    
            std::cin.getline(ch, 256); // this reads the entire input
            cont = ch;
    
        }
    
    
    
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 2017-02-08
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多