簡體   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