一次从输入流读取一个单词到字符数组

Reading one word at a time from input stream into char array?

本文关键字:单词 字符 一个 数组 输入流 一次 读取      更新时间:2023-10-16

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

我的源代码:

#include <iostream>
#include <cstring>
int main()
{
    char ch[256];
    std::cout << "Enter wordsn";
    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,它会读取整个字符串,并且只有当我自己键入字符串"完成"时它才会停止。

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
}
#include <iostream>
#include <string>
int main()
{
    char ch[256];
    std::cout << "Enter wordsn";
    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/

#include <iostream>
#include <string>
int main()
{
    char ch[256];
    std::cout << "Enter wordsn";
    std::string cont;
    while (cont.find("done") == std::string::npos)
    {

        std::cin.getline(ch, 256); // this reads the entire input
        cont = ch;
    }


    return 0;
}