【发布时间】:2015-06-13 00:55:27
【问题描述】:
我正在尝试使用 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。代码中的大部分 cmets 都是我尝试更改为 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
这是当我使用带有数组字符的运算符方法时的输出。
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 方法并不会让它像操作符方法那样返回输入.
我希望我的解释是正确的,我请人翻译一下以帮助我更好地表达它。
谢谢
【问题讨论】:
-
阅读a
std::getlinereference 可能是一个好的开始。就像你现在做的那样,你需要阅读两次。此外,std::getline仅读取字符串,您需要转换为例如自己整数。 -
“试图将读取文件中的第一项放入其中,但显然没有用。” - 发布您的输入和它“不起作用”的确切细节 -您想要和期望发生的事情以及实际发生的事情,以及您对差异的不了解......
-
好的,给我一秒钟发表我的想法