【问题标题】:c++ Get chars individually including spacesc ++单独获取字符,包括空格
【发布时间】:2015-10-21 02:36:15
【问题描述】:

假设我们有这个代码:

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 不会跳过空格,这是我的程序后来导致它们合并的问题。感谢所有 cmets 和帮助。

【问题讨论】:

  • @Matthew 正是如此
  • 也许你需要将输入流告诉not skip spaces
  • 您是否希望将空格添加到nextChar 而不是被跳过?
  • 哦,所以您希望外部 while 循环(inProgram 之一)在检测到空格后结束?
  • 我必须做一些小的改动才能在演示环境中运行,但我相信我已经证明你的“空间检测”代码工作得很好:coliru.stacked-crooked.com/a/eeb3c05e639813e0所以你能提供一个@987654323 @ 请?谢谢。

标签: c++ char spaces


【解决方案1】:

我可以想到以下方法来解决问题。

  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
    }
    

【讨论】:

    猜你喜欢
    • 2017-08-14
    • 2012-07-12
    • 1970-01-01
    • 2022-01-09
    • 2015-01-13
    • 2012-11-11
    • 2021-12-27
    • 1970-01-01
    • 2010-09-12
    相关资源
    最近更新 更多