单独获取字符,包括空格

c++ Get chars individually including spaces

本文关键字:包括 空格 字符 获取 单独      更新时间:2023-10-16

我们有这样的代码:

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不跳过空格,这是后来在我的程序中导致它们合并的一个问题。感谢大家的评论和帮助。

我能想到以下方法来解决这个问题。

  1. 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
    }
    
  2. 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
    }