简体   繁体   中英

How to read numbers from a file as they are written in the file in c++

Hi I'm trying to read numbers from a file and print them exactly how they are written in the

file.

This is how they are written in the file and I want to print them exactly like that.

833 833 835 840 847 850 858 861 866 874 
881 883 892 898 906 915 921 927 936 936 
944 951 953 960 967 975 979 980 989 989 
991 996 997 1001 1001 1001 1001 1002 1006 1011 
1012 1015 1022 1024 1024 1029 1031 1037 1038 1041 

this is my code but it's not doing what I want

void sort(string path){
    fstream fs; 
    fs.open(path); 
    int number; 
    while(fs >> number){
        cout << number << endl;
        }
    }
}

this is the output:

33530
33533
33542
33550
33553
33554
33556
33561
33569

as you can see they are not on the same line.

I even tried this:

void sort(string path){
    fstream fs; 
    fs.open(path); 
    string number; 
    while(getline(fs, number)){
        cout << number << endl;
        }
    }
}

but then the numbers are not integers they are strings

can anyone please help?

Read each line, one by one, and for each line read it into your int number; and output the result.

#include <iostream>
#include <sstream>
#include <string>
#include <utility>

using std::cout;
using std::exchange;
using std::getline;
using std::istream;
using std::istringstream;
using std::string;

static void sort(istream& in){
    string line;

    while (getline(in, line)) {
        istringstream ss(line);
        int number;
        auto sep = "";

        while(ss >> number){
            cout << exchange(sep, " ") << number;
        }

        cout << "\n";
    }
}

static char const* input_data =
R"aw(833 833 835 840 847 850 858 861 866 874
881 883 892 898 906 915 921 927 936 936
944 951 953 960 967 975 979 980 989 989
991 996 997 1001 1001 1001 1001 1002 1006 1011
1012 1015 1022 1024 1024 1029 1031 1037 1038 1041
)aw";

int main() {
    istringstream ss(input_data);
    sort(ss);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM