首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

做习题时遇到的有关问题

2013-12-05 
做习题时遇到的问题#includeiostream#includefstream#includestringusing namespace stdstruct jua

做习题时遇到的问题

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct juan
{
string name;
double qian;
};
int main()
{
ifstream inFile;
inFile.open("scores.txt");
cout << "Enter the number of juan: ";
int u;
inFile >> u;   //txt文件第一排第一个东西就是一个数字 4
cout << u << endl;
inFile.get();   //尝试了两个小时,最后加上这个才算正常运行,但是为什么一定要加啊?
    juan *ch = new juan[u];
juan *sh = new juan[u];
juan *hh = new juan[u];
int i = 0;
int c = 0;
int y = 0;
while (inFile.good())
{
getline(inFile, ch[i].name);
inFile >> ch[i].qian; //上面第一次读取的u后面加了一条inFile.get()才行,而这里又不能加,同样都是读取的数字,为什么后面的加上了inFile.get()反而运行错误了呢?
if (ch[i].qian > 10000)
{
sh[c].qian = ch[i].qian;
sh[c].name = ch[i].name;
c++;
}
else
{
hh[y].name = ch[i].name;
hh[y].qian = ch[i].qian;
y++;
}
i++;
getline(inFile, ch[i].name);
}
cout << "Grand Patrons \n";
for (int x = 0; x < c; x++)
cout << sh[x].name << ":" << sh[x].qian << endl;
cout << "Patrons \n";
for (int x = 0; x < y; x++)
cout << hh[x].name << endl;

return 0;
}


问题都在代码中写出来了,谢谢各位大神了!
[解决办法]
引用:
Quote: 引用:

每一行的末尾有一个回车符号,这个符号你看不见,但它确实存在。自己一个一个元素读入的时候必须考虑跳过这个符号。
否则你以为文件中的字符串是怎么分行的?
恩,这个我理解到了,就是对后面inFile >> ch[i].qian; 这个,按道理说读取了数字之后,应该有个换行符,那么我下次使用getline的时候,是可以直接跳过这个换行符的?
getline 函数调用时,会读delim字符,但是,会把它丢弃。所以调用getline时不需要get,
[解决办法]
getline会读入delim字符,即默认会把换行符读入,但它只作结束符,不会把它写入变量!而使用>>方式从文件中读入变量,会忽略空格,回车,TAB等符号,要使用get()把这些符号读入!
inFile >> u;   //只把整数4读入,而忽略换行符,所以要get()进行读换行符!

热点排行