更具体,我给这个输入:如何从C++中的文件读取时忽略不良数据?
Mo 17 30 15
Sa 9 00 30
Tu 3 30 45
Sq
Fr 21 01 60
字母代表一周中的一天和数字表示时间(二十四小时)和长度通话(分钟)的。
代码工作完美,只要有效的数据输入,但是,像在这种情况下,当广场进入循环分解。我的继承人逻辑至今
while(!instream.eof()){
instream>>c1>>c2;
day = checker(c1, c2);
cout<<c1<<" "<<c2<<endl;
if(day == 0){
instream.ignore(100,'/n');
instream>>c1>>c2;
day = checker(c1, c2);
}
河道内是我的文件对象,C1和C2是char类型的,和功能“检查”检查字符,看是否2的组合是一周中的有效天。如果不是,它从我所了解instream.ignore这些参数会跳过最多100个字符,或者直到一个新行被发现返回0
。问题是,在这个语句运行后,循环终止。 我也可能有一些随机的cout或outstreams在那里,我只是检查的东西。
这里的情况下,IM的完整代码留出一些主要的:
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int checker(char a, char b);
void main(){
ifstream instream;
ofstream outstream;
instream.open("infile.txt");
outstream.open("outfile.txt");
double cost = 0, realtime;
int check = 0, day = 0, hour, min, time, i = 1;
char c1, c2, c3;
while(!instream.eof()){
instream>>c1>>c2;
day = checker(c1, c2);
cout<<c1<<" "<<c2<<endl;
if(day == 0){
instream.ignore(100,'/n');
instream>>c1>>c2;
day = checker(c1, c2);
}
instream>>hour>>min>>time;
realtime = 1.0*hour + min/60.0;
if(day == 1 && (realtime < 7 || realtime > 21)){
cost = 0.15 * time;
outstream<<"The cost of call " << i << " is $" << cost <<endl;
i++;
}
else if(day == 1 && (realtime >= 7 || realtime <= 21)){
cost = 0.30 * time;
outstream<<"The cost of call " << i << " is $" << cost <<endl;
i++;
}
else if(day == 2){
cost = 0.10 * time;
outstream<<"The cost of call " << i << " is $" << cost <<endl;
i++;
}
outstream<<" "<<hour<<endl;
outstream<<" "<<min<<endl;
outstream<<" "<<time<<endl;
outstream<<" "<<i<<endl;
}
cout<<"The program has completed its task"<<endl;
instream.close();
outstream.close();
}
int checker(char a, char b){
int day2 = 0;
if(a == 'M' && b == 'o' || a == 'm'&& b == 'O' || a == 'm'&& b == 'o' || a == 'M'&& b == 'O'){
day2 = 1;
}
else if(a == 'T'&& b == 'u' || a == 't'&& b == 'U' || a == 't'&& b == 'u' || a == 'T'&& b == 'u'){
day2 = 1;
}
else if(a == 'W'&& b == 'e' || a == 'w'&& b == 'E' || a == 'w'&& b == 'e' || a == 'W'&& b == 'E'){
day2 = 1;
}
else if(a == 'T'&& b == 'h' || a == 't'&& b == 'H' || a == 't'&& b == 'h' || a == 'T'&& b == 'H'){
day2 = 1;
}
else if(a == 'F'&& b == 'r' || a == 'f'&& b == 'R' || a == 'f'&& b == 'r' || a == 'F'&& b == 'R'){
day2 = 1;
}
else if((a == 'S'&& b == 'a') || (a == 's'&& b == 'A') || (a == 's'&& b == 'a') || (a == 'S'&& b == 'A')){
day2 = 2;
}
else if((a == 'S'&& b == 'u') || (a == 's'&& b == 'U') || (a == 's'&& b == 'u') || (a == 'S'&& b == 'U')){
day2 = 2;
}
else
day2 = 0;
return day2;
}
--939345676
编辑:感谢您的答复,我同意100%,我应该读它作为一条线,解析字符串,但我目前正在学习一门必需的编程课,虽然之前我已经完全掌握了100%的材料,但我已经用java编写了所有的教程,所以我的语法不太好,而且我们被告知只能使用函数/循环/方法这已经在讲座中讨论过了(为了防止作弊,我猜)。 '\ n'而非'/ n'帮助非常大,哈哈谢谢!
另外,我抓的第一件事是在连续2天差错误..我把它改成了如果0从“检查”返回控制/ else结构捕获所有的坏日子。
的结论。这个网站让我傻笑像一个女学生......程序员谁是好了很多,比我帮助Ø
的社区
当试图在一个文件中读取,你通常要检查'而(instream.good()){...}'而不是'而(!instream.eof()){...}'。 – 2011-03-09 19:41:22
我假设线'instream.ignore(100, '/ N');'应'instream.ignore(100, '\ n');'。 – 2011-03-09 20:20:21