繁体   English   中英

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

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

嗨,我正在尝试从文件中读取数字并准确打印它们在

文件。

这就是它们在文件中的写法,我想完全按照那样打印它们。

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 

这是我的代码,但它没有做我想做的

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

这是 output:

33530
33533
33542
33550
33553
33554
33556
33561
33569

如您所见,它们不在同一条线上。

我什至试过这个:

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

但是数字不是整数它们是字符串

谁能帮忙?

逐行阅读每一行,并将每一行读入您的int number; 和 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