我试图使用istream& getline而不是istream& operator从文件中读取行。
结果cpp
#include "Result.h"
Result::Result()
{
Coursename[0] = '\0';
}
Result::Result( const char * nam, unsigned scor )
{
strncpy( Coursename, nam, CourseNameSiz );
score = scor;
}
//istream& getline( istream & input, Result & Re, ',' )
istream & operator >>( istream & input, Result & Re )
{
//getline(Re.Coursename, input, ',');
input >> Re.Coursename >> Re.score;
return input;
}
ostream & operator <<( ostream & os, const Result & Re )
{
os << " Unit Name: " << Re.Coursename << '\n'
<< " Result: " << Re.score << '\n';
return os;
}
int Result::GetScore() const
{
return score;
}
inline void Result::SetScore( unsigned scor )
{
score = scor;
}结果标头
#ifndef RESULT_H
#define RESULT_H
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
const unsigned CourseNameSiz = 10;
class Result
{
public:
Result();
Result( const char * nam, unsigned scor );
int GetScore() const;
// Get the number of s.
void SetScore( unsigned scor );
// Set the number of score.
//string Result:GetCourseName() const;
friend ostream & operator <<( ostream & os, const Result & Re );
//friend istream & getline( istream & input, Result & Re, ',' );
friend istream & operator >>( istream & input, Result & Re );
private:
char Coursename[CourseNameSiz];
//string Coursename[CourseNameSiz]; // Unit name, C style string
int score; // number of scores
string str;
};
#endif // RESULT_H这一切都是我想要的,但是我需要修改它,所以我不想一次只读一个单词,而是使用带分隔符的istream& getline。代码中的大多数注释都是我试图更改为getline方法的。我制作了一个字符串数组,作为一个测试,我试图将读文件中的第一项放入其中,但显然没有工作。
我只是在这里找个小小的指导。提前感谢
编辑::输入文件: rinput.txt
31525 1 4
JPN_101 3 Japanese, 90,
ICT 4 example1, 91,
TIC 4 example2, 92,
CIT 4 example3, 93因此,在上面写着example1和91的地方,这是我试图用getline作为分隔符的两个条目,因为我想在读取文件中使用空格。
其他信息是在不同的类中读取的,当我让这个类开始工作时,我将更改为getline方法。
输出文件: routput.txt
Student ID: 31525
Semester: 1
Unit: JPN_101
Credits: 3
Unit Name: Japanese
Result: 90
Unit: ICT
Credits: 4
Unit Name: example1
Result: 91
Unit: TIC
Credits: 4
Unit Name: example2
Result: 92
Unit: CIT
Credits: 4
Unit Name: example3
Result: 93
Number of courses = 4
Total credits = 15这是使用带有数组字符的运算符方法的when的输出。
include\Result.h|28|error: expected identifier before ','|
include\Result.h|28|error: expected ',' or '...' before ','|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|,它指向头文件行28,即friend istream & getline( istream & input, Result & Re, ',' );。
我相信我只是不明白为什么只将它更改为字符串数组(string Coursename[CourseNameSiz];),然后仅仅将operator方法更改为getline方法,而不只是让它返回输入,就像对运算符方法那样。
我希望我解释得对,我让人把这个翻译一下,帮我说得更好。
谢谢你
发布于 2015-04-08 08:19:47
这条线
friend istream & getline( istream & input, Result & Re, ',' );不会编译,因为您有一个常量作为第三个参数,而不是参数声明。
在这种情况下,因为在调用getline的方法中硬编码',',所以根本不需要传递逗号。
friend istream & getline( istream & input, Result & Re);类似地,在定义函数时,不需要函数定义中的',':
istream& getline( istream & input, Result & Re)
{
getline(Re.Coursename, input, ',');
return input;
}注意,在对getline的内部调用中仍然需要逗号。
这将修复您列出的编译器错误,如果代码不能正常工作,仍然需要调试代码。
https://stackoverflow.com/questions/29508337
复制相似问题