2013-08-29 66 views
1

我正在通過項目在C++中的歐拉問題,並堅持我的代碼問題22.下面是我的CPP和我得到的答案是871202730,或4448太高。我輸出了排序後的列表,並檢查了一些名字得分是否正確計算,並且我有正確的名字數量。希望這很簡單,我只需要一些新的眼睛來看看它。 Link to the question.項目歐拉#22 C++

#include <iostream> 
#include <fstream> 
#include <algorithm> 
#include <vector> 
#include <string> 
#include <sstream> 
using namespace std; 

int main() { 
    int sum = 0; 
    vector<string> names; 
    char name[50], junk[5]; 
    string str; 
    ifstream inFile; 
    inFile.open("docs/names.txt"); 

    while(!inFile.eof()) { 
     inFile.getline(junk, 50, '/"'); 
     inFile.getline(name, 50, '/"'); 
     stringstream sstr; 
     sstr << name; 
     sstr >> str; 
     names.push_back(str); 
    } 

    sort(names.begin(), names.end()); 

    for(int i=0; i<names.size(); i++) { 
     int namesum = 0; 
     for(int j=0; j<names[i].size(); j++) 
      namesum += (names[i][j] - 64); 
     sum += (namesum*i); 
    } 

    cout << "Sum: " << sum << endl; 
    return 0; 
} 
+0

你爲什麼要使用你的字符文字斜槓?它應該是反斜槓,如果你想逃避雙引號''',你不需要在一個字符字面值中逃避 –

+0

除此之外,不要使用'while(!eof)' ,它並不像你期望的那樣工作,而是使用'while(getline && getline)'。 –

+0

謝謝,正斜槓是一個錯誤,我忘記把它們取出來。使用while(getline)實際上給了我正確的答案,所以也許輸入文件只是最後給我一些垃圾? [SO禮貌Q] - 我現在應該刪除我的問題嗎?或者我可以標記它不再需要? – aswaney

回答

2

當讀取的流,結束文件的標誌沒有被設置,直到輸入操作試圖讀取超出文件的末尾和失敗。這就是爲什麼你不能做到像

while (!inFile.eof()) { ... } 

如果你不喜歡上面,輸入操作將失敗,並沒有正確地更新輸入字符串。

相反,你應該這樣做:

while(inFile.getline(junk, 50, '"') && inFile.getline(name, 50, '"')) { ... }