2014-01-13 198 views
0

我正在做一個簡單的任務,我無法輸出預期的輸出。有人可以幫助我找出問題所在的方向嗎?我們不允許使用istringstream。輸入和輸出文本文件

else 
    { 
     upData >> houseIdent; 

     while(upData) 
     { 

     do{ 
       upData >> vehType >> plate >> year >> vehPrice; 

       calculate = calcReg(vehType, plate, year, 
           vehPrice); 

       outDataOne << fixed << showpoint << setprecision(2); 
       outDataOne << ' ' << vehType << ' ' << plate << ' ' << calculate 
          << endl; 


       ch = upData.peek(); 

      }while (upData && (ch != '\n')); 

      upData >> houseIdent; 

    } 

upData是ifstream .txt,outDataOne是ofstream .txt。輸入與此類似

11111中號DKC294 2007 23001一VID392 2010 10390
22222一DKS382 2011 20390
33333一DKF329 2001 30920中號AJD302 2004年15509

我一直儘管得到的輸出是第一兩條輸出線是正確的,但是第三條線不返回並讀取第二行ID號,但保留11111作爲ID號,同時將vehType設置爲2,將板設置爲0390.我很困惑這個我對C++相當陌生。

在此先感謝

+0

[Works for me](http://ideone.com/HzJoPi) –

回答

0

好了,我把你的代碼,並修改了它稍微所以我可以運行它:

#include <iostream> 
#include <iomanip> 
#include <string> 

int main(int argc, char *argv[]) { 
    #define upData std::cin 
    #define outDataOne std::cout 

    string houseIdent; 
    char vehType; 
    string plate; 
    int year; 
    int vehPrice; 
    int ch; 
    upData >> houseIdent; 
    while (upData) { 
    do { 
     upData >> vehType >> plate >> year >> vehPrice; 

     auto calculate = 237237; // calcReg(vehType, plate, year, vehPrice); 

     outDataOne << std::fixed << std::showpoint << std::setprecision(2); 
     outDataOne << ' ' << vehType << ' ' << plate << ' ' << calculate << endl; 

     ch = upData.peek(); 

    } while (upData && (ch != '\n')); 

    upData >> houseIdent; 
    } 
    return 0; 
} 

而且它餵給你輸入:

11111中號DKC294 2007 23001一VID392 2010 10390 22222 一個DKS382 2011 20390 33333一DKF329 2001 30920中號AJD302 2004年15509

而且它那坑了這一點:

中號DKC294 237237 一個VID392 237237 一個DKS382 237237 一個DKF329 237237 中號AJD302 237237

這似乎是做正確的事。這似乎留下更多的問題比答案,但:

1)請注意,當您調用peek()時,它返回一個int,而不是一個字符,因爲結果可能是一個EOF。您不顯示任何變量的聲明,但這可能是一個小問題。

2)在「更新>> vehType ...」行之後,您不檢查輸入是否已用完。你真的需要這樣做,因爲在你向它提供它不能提供的數據之前,流不會報告EOF。如代碼所示,它看起來可能會在循環的最後一次使用陳舊的數據。

3)你說vehType報告爲2,而板是0390;這可能意味着它將「20390」解釋爲車輛類型的一個字符與其餘字符串的組合。我沒有看到這是怎麼發生的(當我嘗試它時沒有發生),但我的猜測是,你的輸入中有一個隱藏的垃圾字符,它正在拋出一些東西。 (也許unicode non-breaking space或somesuch?)這將大大有助於添加一個調試行,您可以將它讀入的所有vehType/plate/year/vehPrice值打印出來,看看代碼出錯的地方。

+0

我正在看它,它似乎不是讀最後upData >> houseIdent ;.這似乎是輸入被跳過,我想知道爲什麼它被跳過。 – user2649644