我似乎无法从我的txt文件中读取以下任何整数到我的向量中。我有cout矢量的第一个元素只是为了测试矢量是否正确地接受了元素。但是程序.exe在运行时会不断崩溃。除非我删除cout线
#include <iostream>
#include <cstddef>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
fstream fin;
char choice_readfile;
int rowcount;
do //verify choice to read from file is Y,y or N,n
{
cout << "Do you wish to read from file (Y/N)? (file name must be named students.txt)" << endl; //choice for user to read from external file
cin >> choice_readfile;
while(cin.fail())
{
cin.clear();
cin.ignore(80,'\n');
cout << "Please Re-Enter choice" << endl;
cin >> choice_readfile; // choice to read from file
}
}
while(choice_readfile != 'Y' && choice_readfile != 'y' && choice_readfile != 'N' && choice_readfile != 'n');
if(choice_readfile == 'Y' || choice_readfile == 'y')
{
fin.open("students.txt", ios::in|ios::out); //opens mygrades.txt
if(fin.fail())
{
cout << "Error occured while opening students.txt" << endl;
exit(1);
}
fin.clear();
fin.seekg(0);
string line;
while( getline(fin, line) ) //counts the rows in the external file
rowcount++;
cout << "Number of rows in file is " << rowcount << endl;
cout << endl;
}
int i=0, value;enter code here
vector<int>a;
while ( fin >> value ) {
a.push_back(value);
}
cout << a[0];
return 0;
}
答案 0 :(得分:1)
计算文件中的行数后,输入偏移量位于文件末尾。在开始读取整数值之前,需要将其重置为文件的开头。您可以使用seekg
重置输入偏移量。
fin.seekg(0); // move input to start of file.
while ( fin >> value )
{
a.push_back(value);
}