gpt4 book ai didi

c++ - C++中使用getline函数提取某些字符

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:07 26 4
gpt4 key购买 nike

我只需要从文本文件中获取特定字符。我在 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;
}

最佳答案

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

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
...
}

关于c++ - C++中使用getline函数提取某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49041846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com