C++ 如何读取行并更改为整数fstream
我是编程新手,我有一个data.txt文件,其中包含以下内容:C++ 如何读取行并更改为整数fstream,c++,io,C++,Io,我是编程新手,我有一个data.txt文件,其中包含以下内容: bumbumbow 1 0 3 9 8 bumbumbum 1 0 3 9 :0 我想读第2:10398行并把它转换成整数,但我有一个错误 有什么问题?这是我的密码: #include <iostream> #include <fstream> #include <limits> #include<string> #include<vector> std::fs
bumbumbow
1 0 3 9 8
bumbumbum
1 0 3 9 :0
我想读第2:10398行并把它转换成整数,但我有一个错误
有什么问题?这是我的密码:
#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;
}
提前感谢各位由于使用错误的参数1 0 3 9 8调用std::stoi而导致崩溃。 您需要替换std::getlinefile,line2;result=for循环中的std::stoiline2,它将第2行拆分为令牌,并为这些令牌调用std::stoi。例如,您可以在此处看到如何拆分: