我只需要从文本文件中获取特定字符。我在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;
}
答案 0 :(得分: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
...
}
答案 1 :(得分: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";
}