-5

I am trying to read from a file and insert the data into a vector. The file looks like:

16
0100
0111
0111
0001
0100
1011
1010
0010
0110
1001
1100
1001
1100
0101
0101
0001

I want my vector to look something like:

16 0 1 0 0 0 1 1 1 0 1 1 1...

My code looks like this:

void readFile(string name){
    ifstream fin;
    vector<int> graphData;
    int y;
    fin.open(name);
    if (!fin.is_open()){
        cout << "Error: Could not open data.";

    }
    else{
        while(!fin.eof()){
            fin >> y;
            graphData.push_back(y);
        }

    }
    fin.close();
    for(int i = 0; i < graphData.size(); ++i){
        cout << graphData[i] << " ";
    }
}

I am pretty sure the issue is with me defining y and then trying to push that in. But when I run the code nothing is outputted like the vector is empty.

pasha
  • 2,035
  • 20
  • 34
K22
  • 147
  • 1
  • 5
  • 15

3 Answers3

1

Try reading the numbers as character strings:

unsigned int quantity = 0;
fin >> quantity;
fin.ignore(100000, '\n');
std::string number_text;
vector<int> binary;
while (getline(fin, number_text))
{
  for (int i = 0; i < number_text.length())
  {
    int bit = number_text[i] - '0';
    binary.push_back(bit);
  }
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
1

You could - after skipping the line count - read in each individual character and compare it to '0' or '1'. See the following code:

int main() {

    vector<bool> bits;
    ifstream f(DATAFILE);
    if (f.is_open()) {
        int dummy;
        f >> dummy;
        char c;
        while (f >> c) {
            if (c == '1') {
                bits.push_back(true);
            }
            else if (c=='0') {
                bits.push_back(false);
            }
        }
        f.close();
        for(int i = 0; i < bits.size(); ++i){
            cout << bits[i] << " ";
        }
    }
    return 0;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

You should use getline function to get input line by line: After fin.open(name);

do this:

getline(fin,line);

and then save the line to your y

pasha
  • 2,035
  • 20
  • 34