一次从输入流读取一个单词到字符数组
Reading one word at a time from input stream into char array?
我试图让我的程序一次读取一个单词,直到检测到单词"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;
}
相关文章:
- 当您在此单词中搜索单词时调整字符数组的大小?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- C ++程序在字符数组中插入单词
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- 延迟逐个字符打印单词
- 创建单词对齐的字符向量
- 在字符数组中存储和恢复一组单词
- 如何用单词排列向量中的每个字符升序?
- 如何在字符指针数组中保留指向每个单词的指针?
- 当找到来自 RHS 的字符"\"时,从主字符串中获取单词或子字符串,然后擦除其余部分
- 视觉C++查找以 "ing" 结尾且少于或等于 10 个字符的单词
- 需要将单词的文本文件存储到C 中的字符阵列中
- 从字符数组中删除单词
- 忽略给定单词之前的所有字符
- 如何计算C++字符数组中的单词
- 如何用新单词替换未知数量的相同字符
- (C++) 打印字符数组字符串的单词时出现问题
- 计数句子中单词的字符数
- 如何计算两个文件中字符单词和行的总数,并将它们相加以得出总数
- 我如何写一个Qt正则表达式来突出显示字符串开始和结束与非单词字符