|
代码如下,输出的文件中没有内容……不知道为嘛……哪里有问题么?为什么?要怎么修改? #include<iostream>
#include<cstring>
#include<vector>
#include<fstream>
#include<cstdlib>
using namespace std;
class Student_Info{
public:
vector<char> name;
vector<double> score;
};
int main()
{
Student_Info S;
char name;
double score;
vector<char>::const_iterator n;
vector<double>::const_iterator s;
ofstream OutFile("students.txt", ios::out|ios::binary );
while (cin >> name >> score){
S.name.push_back(name);
S.score.push_back(score);
}
for (n = S.name.begin(); n != S.name.end(); n++){
for (s = S.score.begin(); s != S.score.end(); s++){
OutFile << *n << " " << *s << endl;
}
}
OutFile.close();
system("pause");
return 0;
}
|
|
| 5分 |
测试数据是什么, 我怀疑char name这里有问题,这样定义只能输入一个字符,第二个字符非数字就会导致while失败,改成string及相应vector的地方改下试试
|
| 10分 |
while (cin >> name >> score){
S.name.push_back(name); S.score.push_back(score); } for (n = S.name.begin(); n != S.name.end(); n++){ for (s = S.score.begin(); s != S.score.end(); s++){ OutFile << *n << ” ” << *s << endl; } } 1.你的输入是说:一个name对应一个score,但是你写入文件的时候,一个name对应N个score; 2.你确定你的push_back成功了吗?你在输入文件的时候可以先输出看一遍.(我怀疑你输入失败了) |
|
乍看起来c++的cin、cout在输入、输出上比c的scanf、printf简单,不用格式控制符!
但是不用格式控制符,输入输出恰好是你期望的格式的时候好说;等到输入输出不是你期望的格式的时候,你就会觉得还是用格式控制符更方便、更靠谱。 摒弃cin、cout! 使用scanf、printf。 |
|
| 5分 |
找个空闲,帮你看了一下,你把写文件的部分两个for循环改掉(一个即可,不然逻辑错误).然后添加:OutFile.flush()刷新一下输出缓存即可.
|
|
刷新缓冲取 的
|
|
|
的确……输入失败了……我把vector<char>换成了string,然后就成功了~ |
|
|
是的,用char的时候输入失败了~ |
|
|
多谢多谢,这个我之前没意识到,由于经验不足…… |
|
|
多写一点,code前想清楚即可. |
|