使用C ++中的getline函数来提取某些字符

问题描述 投票:1回答:2

我只需要从文本文件中获取特定字符。我在C ++中使用getline()函数。我的编译器一直给我一个错误,即getline()没有匹配的成员函数调用,我该如何解决?我正试图从文件中提取姓氏和分数。

该文件看起来像:

Weems 50 60

Dale 51 60

Richards 57 60
...

这是我正在尝试的代码:

#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

int main ()
{
    //input variables
    float GradeScore;
    float TotalPoints;
    float GradePercent;
    string LastName;

    ifstream myFile;

    //open file
    myFile.open ("/Users/ravenlawrence/Documents/TestGrades.rtf",ios::in);
    // if file is open
    if (myFile.is_open()) {
        while(!myFile.eof()) {
            string data;
            getline(myFile,data); //reading data on line
            myFile.getline(LastName, ' ');//storing data in LastName 
            myFile.getLine(GradeScore,' ');//storing data in GradeScore 
            myFile.getLine(TotalPoints,' ');//storing data in Total Points 
            cout << LastName << endl;
            // cout<<data<<endl; //print it out
        }
    }
    return 0;
}
c++ fstream getline
2个回答
0
投票

从设计开始,将工作分解为小步骤:

open file
loop, reading line from file while more lines
    split line into fields
    convert fields into variables
    display variables

现在解决每一步

// open file
ifstream myFile ("/Users/ravenlawrence/Documents/TestGrades.rtf",ios::in);
if( ! myFile ) {
  cerr << "cannot open file\n";
  exit(1);
}

//loop, reading line from file while more lines
string data;
while( getline( myFile, data ) ) {

   // split line into fields
   std::stringstream sst(data);
   std::string a;
   std::vector<string> vfield;
   while( getline( sst, a, ' ' ) )
       vfield.push_back(a);

   // ignore lines that do not contain exactly three fields
   if( vfield.size() != 3 )
      continue;

   //convert fields into variables
   LastName = vfield[0];
   GradeScore = atof( vfield[1].c_str() );
   TotalPoints = atof( vfield[2].c_str() );

   // display
   ...
}

0
投票

你不需要在这里使用函数getline,你可以逐字读取文件。其次,你需要在文件到达eof后关闭它。这是代码:

   int main()
   {
       //input variables
         float GradeScore;
         float TotalPoints;
         float GradePercent;
         string LastName;

         ifstream myFile;

       //open file
         myFile.open("check.txt", ios::in);
      // if file is open
         if (myFile.is_open()) {

           while (!myFile.eof()) {

              myFile >> LastName;//storing data in LastName 
              myFile >> GradeScore;//storing data in GradeScore 
              myFile >> TotalPoints;//storing data in Total Points 

              cout << LastName << endl;
           // cout<<data<<endl; //print it out
           }

         myFile.close();
      }
      system("pause");
      return 0;
      }

而不是检查文件是否打开更好的方法是检查文件是否存在:

        if(!myfile)
        {
          cout<<"error!file donot exist";
         }
© www.soinside.com 2019 - 2024. All rights reserved.