2012-04-04 75 views
0

我正在嘗試解決項目euler的問題13,它涉及100個50位數字的總和。我認爲這會比將整塊數字粘貼到我的代碼中更好。所以我搜索了四周,發現你可以將塊粘貼到一個.txt文件並從那裏讀取。從.txt讀取

那麼,我將如何去閱讀從C++中的.txt文件,更重要的是從中分別獲取50位數字的字符串?

+0

你知道['std :: ifstream'](http://en.cppreference.com/w/cpp/io/basic_ifstream)? – 2012-04-04 09:58:20

回答

2

是這樣的嗎?

// reading a text file 
#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() { 
    string line; 
    ifstream myfile ("numbers.txt"); 
    if (myfile.is_open()) 
    { 
    while (myfile.good()) 
    { 
     getline (myfile,line); 
     int i = atoi(line.c_str()); 
     // do here something with 'i' 
     cout << i 
    } 
    myfile.close(); 
    } 

    else cout << "Unable to open file"; 

    return 0; 
} 
+1

啊,當然你不能將50位數字轉換爲int,但我想這是另一個問題:) – 2012-04-04 10:03:26

+2

我會跳過對'is_open'的檢查並使用while(getline(...) )'而不是。 – 2012-04-04 10:05:30

+0

@Khôi我如何從.txt獲得第一行或第二行? – cortex 2012-04-04 10:16:35