2015-11-03 194 views
0

目標是讀取以下文件中的每個整數並將它們全部添加。但是由於某種原因,我似乎無法將字符串行轉換爲int。 代碼:FStream - 讀取文件內部的整數C++

#include <iostream> 
#include <fstream> 
using namespace std; 

int main(){ 

string line; 
ifstream file ("Random.txt"); 
int lines; 
int amount = 0; 
while(getline(file, line)){ 
    lines++; 
    amount += static_cast<int>(line); 
} 

cout << amount; 
return 0; 

} 

txt文件:

2 
3 
4 
6 

任何幫助,將不勝感激

回答

0

一投不這樣做正確的工具,它適用於僅兼容類型。

你真正需要的是一個轉換功能:

amount += std::stoi(line); 

reference docs請。

+0

感謝但我得到這個錯誤:[錯誤]「Stoi旅館」不是「性病」 –

+0

成員@TylerEsposito你有沒有'#include '? –

+0

更好地直接使用'ifstream'來讀取'int'。 – JSQuareD

2

不,你不能將這樣的字符串轉換成任何東西,真的。

如果知道該文件只包含整數,你可以閱讀他們直接:

int number; 
while (file >> number) 
{ 
    ++lines; 
    amount += number; 
} 
+0

工作很好!謝謝! –