【问题标题】:how to read line and change to integer numbers fstream如何读取行并更改为整数 fstream
【发布时间】:2016-04-15 10:42:14
【问题描述】:

我是编程新手,我有一个 data.txt 文件,内容如下:

bumbumbow

1 0 3 9 8

bumbumbum

1 0  3 9 :0

我想读取2: 1 0 3 9 8 行并将其转换为整数,但出现错误。

有什么问题?这是我的代码:

#include <iostream>
#include <fstream>
#include <limits>
#include<string>
#include<vector>

std::fstream& GotoLine(std::fstream& file, unsigned int num) {
    file.seekg(std::ios::beg);
    for (int i = 0; i < num - 1; ++i) {
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return file;
}

int main() {
    int result, i = 0;
    std::vector<int> Array;
        using namespace std;
        std::fstream file("data.txt");

        GotoLine(file, 2);

        std::string line2;
        std::getline(file, line2);





        for (int result; std::getline(file, line2); result = std::stoi(line2))
        {
            Array.push_back(result);

            std::cout << "Read in the number: " << result << "\n\n";
        }


        return 0;

}

先谢谢各位了

【问题讨论】:

    标签: c++ io


    【解决方案1】:

    由于使用错误的参数“1 0 3 9 8”调用std::stoi()而发生崩溃。

    您需要将 for 循环内的 std::getline(file, line2); result = std::stoi(line2) 替换为将 line2 拆分为令牌并为这些令牌调用 std::stoi() 的东西。例如,您可以在此处查看如何拆分: Right way to split an std::string into a vector<string>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多