[英]Using the getline function in C++ to extract certain characters
我只需要從文本文件中獲取特定字符。 我在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
...
}
您不需要在這里使用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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.