2013-12-21 52 views
2

我有一個file.txt的如:讀取和存儲整數在文件

15 25 32 // exactly 3 integers in the first line. 
string1 
string2 
string3 
* 
* 
* 
* 

我想要做的是,閱讀15,25,32並將它們存儲到可以說INT A,B, C;

有人幫我嗎?提前致謝。

回答

1

可以使用std::ifstream讀取文件內容:

#include <fstream> 
std::ifstream infile("filename.txt"); 

然後你可以使用std::getline()閱讀與數字行:

#include <sstream> 
#include <string> 
std::string line; 
std::getline(infile, line); 

然後,你可以使用一個std::istringstream解析存儲在該行的整數:

std::istringstream iss(line); 
int a; 
int b; 
int c; 

iss >> a >> b >> c; 
+0

yeap,非常感謝! – caesar

+1

不客氣。請注意,@ KerrekSB的答案也顯示錯誤檢測。 –

+0

@ Mr.C64:是的,如果提取失敗,訪問'a','b'或'c'可能是未定義的行爲。 –

2

標準的成語使用輸入輸出流:

#include <fstream> 
#include <sstream> 
#include <string> 

std::ifstream infile("thefile.txt"); 

std::string first_line; 

if (!infile || !std::getline(first_line, infile)) { /* bad file, die */ } 

std::istringstream iss(first_line); 
int a, b, c; 

if (!(iss >> a >> b >> c >> std::ws) || iss.get() != EOF) 
{ 
    // bad first line, die 
} 

// use a, b, c 
相關問題