gpt4 book ai didi

c++ - 一次从输入流中读取一个单词到 char 数组?

转载 作者:行者123 更新时间:2023-11-28 06:31:00 26 4
gpt4 key购买 nike

我试图让我的程序一次读取一个单词,直到检测到单词“done”。但是,我似乎无法获得正确的语法,首先如您所见,我使用了读取整行的 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::istream::getline()std::istream::get() 之间的区别(char 数组version) 是后者不提取终止符,而前者提取。如果你想阅读格式化并在第一个空格处停止,你会使用输入运算符。将输入运算符与 char 数组一起使用时,请确保您设置了数组的宽度,否则您会为您的程序创建一个潜在的溢出(和攻击 vector ):

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
}

关于c++ - 一次从输入流中读取一个单词到 char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27583323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com