2016-04-15 100 views
0

我有一個data.txt文件,其內容是:如何讀取特定文件fstream?

[exe1] 

1 0 2 9 3 8 
---------- 


[exe2] 


---------- 
10 2 9 3 8:0 

我想讀第2行:1 0 2 9 3 8。但我的輸出只有1

我的代碼:

#include <iostream> 
#include <fstream> 
#include <limits> 
#include<string> 

std::fstream& GotoLine(std::fstream& file, unsigned int num) { 
    file.seekg(std::ios::beg); 
    for (int i = 0; i < num - 1; ++i) { 
     file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    } 
    return file; 
} 

int main() { 


     using namespace std; 
     fstream file("data.txt"); 

     GotoLine(file, 2); 

     std::string line2; 
     file >> line2; 

     std::cout << line2; 
     cin.get(); 
     return 0; 

} 

什麼是我的問題嗎?對不起,我是編程新手。

回答

3

file >> line2;將停止讀取第一個空格,因此只讀取「1」,因爲提取operator >>使用空格作爲分隔符。

您可能需要使用getlinegetline(file,line2)

+0

它的工作原理,謝謝 – dinhvan2804

2

輸入操作>>讀取空格分隔字符串,如果你想閱讀你需要使用一整行std::getline

std::string line2; 
std::getline(file, line); 
+0

是的,它的工作原理,謝謝 – dinhvan2804