【发布时间】:2025-11-22 18:55:01
【问题描述】:
我有一个关于在 C++ 中读取文本文件的问题。
假设我有一个这样的 sample.txt 文件:
2
8 5
1 1 1 2 3 4 5 6
4 7
1 2 3 4
文件的第一行表示实例的数量(这里是 2 个实例)。第二行和第三行是关于第一个实例的信息。第三行和第四行代表第二个实例。 以下是我读取此文本文件的主要功能。但是当我运行它时,它只是不起作用。即阅读过程无法继续。任何人都可以帮助我。
int main()
{
int number;
string filePath;
int numberOfInstances;
int Max;
int Rings;
cout << "please input your file path: " ; //ie, D:\\sample.txt
cin >> filePath;
ifstream fin;
fin.open(filePath.c_str());
if(fin.fail()) {
cout << "sorry, fail to open" << endl;
exit(1);
}
fin >> numberOfInstances;
vector<int> vect1;
for(int i = 0; i < numberOfInstances; i++) {
fin >> Rings;
fin >> Max;
for(i = 0; i < Rings; i++) {
fin >> number;
vect1.push_back(number);
}
//
//code to process Vect1, eg, sort it
//
for(i = 0; i < Rings; i++) {
vect1.pop_back();
}
}
fin.close();
return 0;
}
【问题讨论】:
-
您可以使用
getline()函数从流中读取一行。