单独获取字符,包括空格
c++ Get chars individually including spaces
我们有这样的代码:
char nextChar;
std::string nextTerm;
bool inProgram = true;
while (inProgram)
{
std::cin.get(nextChar);
while (nextChar != ' ')
{
nextTerm.push_back(nextChar);
std::cin.get(nextChar);
}
//Parse each term until program ends
}
基本上,我这里的目标是单独获取每个字符并将其添加到字符串(nextTerm)中,直到它遇到空格,然后停止解析术语。当输入两个单词时,这似乎只是跳过空格,直接从下一个单词中获取字符。这似乎是简单的,但我不能弄清楚。谢谢你的帮助。
编辑:结果是get不跳过空格,这是后来在我的程序中导致它们合并的一个问题。感谢大家的评论和帮助。
我能想到以下方法来解决这个问题。
-
在
while
内环前清除nextTerm
char nextChar; std::string nextTerm; bool inProgram = true; while (inProgram) { // Clear the term before adding new characters to it. nextTerm.clear(); std::cin.get(nextChar); while (nextChar != ' ') { nextTerm.push_back(nextChar); std::cin.get(nextChar); } //Parse each term until program ends }
-
将
nextTerm
的定义移到while
外环中char nextChar; bool inProgram = true; while (inProgram) { // A new variable in every iteration of the loop. std::string nextTerm; std::cin.get(nextChar); while (nextChar != ' ') { nextTerm.push_back(nextChar); std::cin.get(nextChar); } //Parse each term until program ends }
相关文章:
- 2D数组来自文本输入,中间有空格
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 为什么 cmake 许可证<>样式不包括?
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 计算平均值,不包括上次得分
- 从多个源构造一个对象,包括一个对象向量
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 移除前面有空格的前2个字符串
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 文件读取C++包括空格键
- 解析C++中的完整(从头到尾)字符串,包括所有空格
- 回文,不包括特殊字符和空格
- 将文本写入文件,包括空格
- 如何仅测试字符数组的字母(包括空格)
- 从字符串中删除空格,不包括 " 和 ' C++对之间的部分
- 单独获取字符,包括空格
- 读取整行,包括来自 fstream 的空格