繁体   English   中英

无法将整数从txt文件读取到矢量

[英]unable to read integers from txt file to vectors

我似乎无法从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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM