更具體,我給這個輸入:如何從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