Miguel Duran Diaz
Miguel Duran Diaz

Reputation: 312

list.push_back seems to duplicate the last added element

Input: This_is_a_[Beiju]_text

Expected output: This_is_a_[Beiju]_text

Actual output: This_is_a_[Beiju]_textt

It seems when the code ends, it adds an extra unwanted char (note the extra "t" at the end). Code:

#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;
}

Upvotes: 0

Views: 50

Answers (1)

Joel Filho
Joel Filho

Reputation: 1300

This happens because of the newline character.

Your input is actually This_is_a_[Beiju]_text\n. When cin peeks the \n it doesn't see an EOF yet. When operator>> then tries to read the next character, it fails, because it ignores the line break as whitespace and then hits the EOF. And so the value of current_char stays the same as the previous read. Which means you'll insert a duplicate of the last character into your list.

You can use this instead:

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

cin evaluates to false when it reaches EOF, i.e. it will stop the loop if it can't read anything anymore.

Upvotes: 3

Related Questions