-1

I am trying to understand what is happening here, I made this from the program I am working on to show what is happening. The strings pulled from the text file don't match when I compare them to string. But hard coded data will.

this program should be showing:

failed again
failed again
success
success

but is does not, it fails to match the first instance of a55555555. I have found that this only happens on information I pull from the file, so I figure I must be doing something wrong during the import but I can find what. actual output:

failed again
failed again
failed again
success

the file(student.txt):

a22222222
a11111111
a55555555

the code:

#include <vector>
#include <iostream>
#include <fstream>
using namespace std;

class Student {
    public:
        void display(ostream& os) const;
        void setId(string);
        string getId();     
    private:
        string id_;
};

void Student::setId(string id) {
    id_ = id;
}

string Student::getId() {
    return id_;
}


int main () {

    vector <Student> vStudent;
    int count = 0;
    string line;
    ifstream infile("student.txt");

    while (getline(infile, line)) {
        vStudent.push_back(Student());
        vStudent[count].setId(line);
        count++;
    }

    vStudent.push_back(Student());
    vStudent[count].setId("a55555555");

    string test = "a55555555";
    for (auto & element : vStudent) {
        if (test == element.getId())
            cout << "success" << endl;
        else
            cout << "failed again" << endl;
    }   
}
ZeroScifer
  • 53
  • 8
  • This looks very similar to your [previous question](http://stackoverflow.com/questions/28640796/compare-not-matching-a-string-pulled-from-an-object). – Retired Ninja Feb 21 '15 at 09:25

1 Answers1

0

Well, in the first instance, copying your code and test data, I get the expected correct result. So what could be going wrong?

I suspect it is an end-of-line character issue. If, for example, the student.txt file was created in a DOS/Windows environment, and had CR + NL style end of line characters, the lines you read in say a Unix environment will include those CR characters, and consequently the match will fail.

It could be even more simple: there might be white space at the ends of those lines, or some of them, which can be hard to notice until something like this goes wrong.

A potential fix then would be to remove all trailing white space from each read line before setting the id, e.g.:

#include <cctype>
/* ... */
    while (getline(infile, line)) {
        vStudent.push_back(Student());
        while (!line.empty() && std::isspace(line.back())) line.pop_back();
        vStudent[count].setId(line);
        count++;
    }
/* ... */

This will catch spurious spaces, and any errant trailing carriage return.

halfflat
  • 1,584
  • 8
  • 11