2012-12-12 64 views
1

讀取多種類型的可以說我有這樣的文件IO從文件

6 3 
john 
dan 
lammar 

我可以閱讀數字的文本文件,我可以讀的名字,只有當他們在不同的文件。但是這裏的數字和名字都在一個文件中。我如何忽略第一行並直接從第二行開始閱讀?

int main() 
{ 
vector<string> names; 
fstream myFile; 
string line; 
int x,y; 
myFile.open("test.txt"); 
    //Im using this for reading the numbers 
while(myFile>>x>>y){} 
//Would use this for name reading if it was just names in the file 
while(getline(myFile,line)) 
    names.push_back(line); 
cout<<names[0]; 
return 0; 
} 
+0

你能分享一些你的代碼片斷?這將有助於瞭解在哪裏進行改進。 – Smit

+0

你總是可以閱讀所有內容,並分離出你以後不想要的東西。 – Max

+0

你唯一的問題是第一次。保持myFile >> x >> y;並在周圍失去了一段時間。 – jmucchiello

回答

0

如果您使用fstream的只是調用忽略()方法:

istream& ignore (streamsize n = 1, int delim = EOF); 

所以它變得非常簡單:

ifstream file(filename); 
file.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore the first line 

// read the second line 
string name; getline(flie, name); 
1

我不知道我是否有你的權利但如果你總是想跳過第一行 - 你可以簡單地跳過它?

int main() 
{ 
    vector<string> names; 
    fstream myFile; 
    string line; 
    int x,y; 
    myFile.open("test.txt"); 
    //skip the first line 
    myFile>>x>>y; 
    //Would use this for name reading if it was just names in the file 
    while(getline(myFile,line)) 
    names.push_back(line); 
    cout<<names[0]; 
    return 0; 
} 
0

嘗試這樣:

int main() 
{ 
    std::vector<std::string> names; 
    std::fstream myFile; 
    myFile.open("test.txt"); 
    if(myFile.is_open()) 
    { 
     std::string line; 

     if (std::getline(myFile, line)) 
     { 
      std::istringstream strm(line); 

      int x, y; 
      strm >> x >> y; 

      while (std::getline(myFile, line)) 
       names.push_back(line); 
     } 

     myFile.close(); 

     if(!names.empty()) 
      std::cout << names[0]; 
    } 
    return 0; 
}