我似乎无法从txt文件中将以下任何整数读取到向量中。我已经指出了向量的第一个元素,只是为了测试看向量是否正确地吸收了元素。但是程序.exe在我运行时不断崩溃。除非我删除提示行

#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;
 }

最佳答案

计算文件中的行数后,输入偏移量位于文件的末尾。在开始读取整数值之前,需要将其重置为文件的开头。您可以像这样用seekg重置输入偏移。

fin.seekg(0); // move input to start of file.
while ( fin >> value )
{
    a.push_back(value);
}

关于c++ - 无法将整数从txt文件读取到 vector ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27496056/

10-11 23:20
查看更多