【问题标题】:Bug: Why does this getline only loop once?错误:为什么这个 getline 只循环一次?
【发布时间】:2017-01-25 05:16:08
【问题描述】:
while(getline(data, word, '\n')){//seperates by line
    ss<<word; // output1: Chicken, for sale, 60
              // output2: Microwave, wanted, 100 (and so on)

    while(getline(ss, word, ',')){//seperates by individual words + space
        // output1: Chicken
        // output2: for sale
        // output3: 60
        if(word[0]==' '){ //removes space in 2 and 3
            word.erase(0,1);
        }

        if(wordindex==0){
            board[i].object=word;
            wordindex++;
        }
        else if(wordindex==1){
            board[i].type=word;
            wordindex++;
        }
        else if(wordindex==2){
            board[i].price=word;
            wordindex=0; //resets index to 0 for next line
            i++; //moves to next struct in array
        }
    }
}

第二个 getline 循环只为第一个输入循环一次:chicken, for sale, and 60,并且不会到达第二个。我认为单词索引始终设置为0,所以这应该不是问题。此外,第一个getline() 完全输出所有数据,所以有些东西导致第二个getline() 感到困惑。我只是看不到它是什么。

【问题讨论】:

  • 您可能会发现,几乎可以肯定,您的开发环境附带的调试软件可以非常有效地找出问题所在。
  • 另外,另一位用户之前提出了一个类似解析问题的问题。事实证明,在空格上使用 &gt;&gt; 解析并去掉逗号更容易。一方面,它将整数保持为整数。 stackoverflow.com/a/41840993/4581301
  • 我的解析其实很简单。

标签: c++


【解决方案1】:

这里

ss<<word;

OP 重用了一个字符串流,该字符串流可能已在上一次迭代中读到末尾,将流设置为无法再写入或读取的错误状态。这可以通过添加来解决

ss.clear();

在循环结束时删除任何错误标志,但通过不断将 mor 数据写入字符串流,它将继续增长,吸收越来越多的内存,除非用类似的东西清空

ss.str(std::string());

将其内部缓冲区设置回空字符串。如果增加的构造和破坏对解析速度的成本不是问题,那么每次迭代创建一个新的stringstream 可能会更好,只是为了代码清晰。

这是内部解析循环的一种更简单的方法:

std::stringstream ss(word);
while(i<MAX_ARRAY_SIZE && // prevent overflow
      getline(ss,  board[i].object, ',') && 
      getline(ss, board[i].type, ',') && 
      getline(ss, board[i].price, ',')){ // read all three parameters directly into object
    //sanitize
    if(board[i].type[0]==' '){ 
        board[i].type.erase(0,1);
    }

    if(board[i].price[0]==' '){ 
        board[i].price.erase(0,1);
    }
    i++; // next, please
}

【讨论】:

  • 在第一个循环开始时创建一个新的字符串流解决了这个问题。现在我有一个分段错误错误,但这是我可以处理的。
  • @grilam14 检查您是否没有超出阵列。刚刚添加了一个快速破解示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多