【问题标题】:list.push_back seems to duplicate the last added elementlist.push_back 似乎复制了最后添加的元素
【发布时间】:2020-05-27 00:22:37
【问题描述】:

输入:this_is_a_[Beiju]_text

预期输出:This_is_a_[Beiju]_text

实际输出:this_is_a_[Beiju]_textt

似乎当代码结束时,它添加了一个额外的不需要的字符(注意末尾额外的“t”)。 代码:

#include <iostream>
#include <list>

using namespace std;
int main() {
    list <char> text;
    char current_char;
    while(true){
        // Revisa si llegamos al final del archivo
        if(cin.peek() != char_traits<char>::eof()){
            cin >> current_char;
            text.push_back(current_char);
        }
        else{
            break;
        }
    }
    for (auto itr = text.begin(); itr != text.end(); itr++){
        cout << *(itr);
    }

    return 0;
}

【问题讨论】:

    标签: c++ list


    【解决方案1】:

    这是因为换行符。

    您的输入实际上是This_is_a_[Beiju]_text\n。当cin 偷看\n 时,它还没有看到EOF。当operator&gt;&gt; 然后尝试读取下一个字符时,它失败了,因为它忽略了作为空格的换行符,然后点击了 EOF。因此current_char 的值与之前读取的值相同。这意味着您将在列表中插入最后一个字符的副本。

    你可以改用这个:

    while(cin >> current_char){
      text.push_back(current_char);
    }
    

    cin 在到达 EOF 时计算为 false,即如果它无法再读取任何内容,它将停止循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 2019-01-07
      • 2015-08-04
      • 1970-01-01
      • 2018-06-17
      • 2020-07-25
      • 1970-01-01
      相关资源
      最近更新 更多