0
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <sstream> using namespace std;

void printer(int i) {
    cout << setw(4) << i << ", "; }

int main() {
    string s;
    getline(cin, s);
    stringstream input(s); //LINE I
    vector<int> v1;
    int i;
    do {
        input >> hex >> i;
        v1.push_back(i); //LINE II
    } while (!input.fail());
    for_each(v1.begin(), v1.end(), printer);
    return 0; }

Similarly this program outputs t, r, e, e, for file content t r e. I believe the reason is very similar to above question.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <fstream>
using namespace std;
void printer(char c) {
        cout << setw(2) << c << ", ";
}
int main ()
{
        ifstream inputfile("input.txt");
        vector<char> v1;
        char c;
        do 
        {
                inputfile>>c;//LINE I
                v1.push_back(c);
        } 
        while (inputfile.good());//LINE II
        inputfile.close();
        for_each(v1.begin(), v1.end(), printer);
        return 0;
}

These are questions from an assessment. I need to understand the why. Of course, knowing the correction would improve my skills too. But I need to explain why it does not work that way.

Ely
  • 10,860
  • 4
  • 43
  • 64
  • 1
    You need to check `good` / `fail` *before* doing `push_back` – M.M Dec 09 '15 at 07:52
  • Ok, but why? These are assessment questions. I just need to understand the why. I am not expected to correct the program, though it probably helps to understand better. – Ely Dec 09 '15 at 07:58
  • 1
    Why do you have to check whether you got new data before you add it to a collection? Because if you don't, the last time in the loop when you don't get new data, you'll add the old data again. – David Schwartz Dec 09 '15 at 08:11
  • @DavidSchwartz I don't get it. It should consume the last letter *e*. Then it should consume nothing, right? Or do you mean that `c` is not assigned a value and keeps the last `char`? – Ely Dec 11 '15 at 13:15
  • @Elyasin Whatever value `c` has, you call `push_back` again when you shouldn't. – David Schwartz Dec 11 '15 at 15:24

2 Answers2

2

You first try to read, then push the result to vector, than check if an error occured. That order is wrong.

while (true) {
    input >> hex >> i;
    if (input.fail())
        break;
    v1.push_back(i);
}
Lapshin Dmitry
  • 1,084
  • 9
  • 28
1

Replace

do 
{
        inputfile>>c;//LINE I
        v1.push_back(c);
} 
while (inputfile.good());//LINE II

with

input >> hex >> i;
while (!input.fail()) {
    v1.push_back(i); //LINE II
    input >> hex >> i;
}

Note the second version is also correct if your input is empty. First check your input then insert it into vector.

Lukáš Bednařík
  • 2,578
  • 2
  • 15
  • 30