简体   繁体   English

如何从文件中读取数字,因为它们写入 c++ 中的文件

[英]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:这是 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;逐行阅读每一行,并将每一行读入您的int number; and output the result.和 output 结果。

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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