0

There is a text file containing two columns of numbers such as:

4014 4017
4014 4021
4014 4023
4014 4030
4014 4037
4014 4038
4016 4025
4017 4021
4017 4026
4017 4030
4018 4023
4018 4030

and a C++ program reading the file using this code found here

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

int main() {
list<int> v_list, u_list, v_unique_sorted_list;
ifstream infile("text.txt");

int v, u;

while (infile >> v >> u)
{
    v_list.insert(v_list.end(), v);
    u_list.insert(u_list.end(), u);

    cout << v << " " << u << endl;
}

I'm using CLion and the output on the run console is:

3880 3908
38803982 3994
3982 399

3824 3902
38243873 3943
3873 3948

3986 4033
3987 40124016 4025
4017 4021

This is part of the output. The actuall output is very big. Why is my reading scrambled??

Community
  • 1
  • 1
Oh hi Mark
  • 153
  • 1
  • 8
  • 28

1 Answers1

0

Your problem is that there's a newline on all of the lines of your input file (except for the last line, of course).

For this reason, I tend to use std::getline instead of just extracting the data directly. This should work for you:

#include <iostream>
#include <sstream>
#include <list>
#include <string>
#include <fstream>

int main() {
    std::list<int> v_list, u_list, v_unique_sorted_list;

    std::ifstream fin("text.txt");
    std::string line;

    // while we can get data from the input file
    while(std::getline(fin, line)) {
        // put the line in a stream
        std::stringstream ss(line); 
        int v, u;

        // extract two ints from the stream
        ss >> v >> u;

        std::cout << v << " " << u << std::endl;

        v_list.insert(v_list.end(), v);
        u_list.insert(u_list.end(), u);
    }
}
erip
  • 16,374
  • 11
  • 66
  • 121
  • 1
    This was the second example on the link I posted. It gave me the same results, although I will test it tomorrow to be sure. – Oh hi Mark Feb 16 '16 at 14:05
  • Oops. I didn't see that link! This should definitely work, though. You're not consuming newlines. – erip Feb 16 '16 at 14:06
  • There must be something wrong with your data (i.e., maybe there are carriage returns sprinkled in with newlines). – erip Feb 17 '16 at 12:27