2012-12-12 63 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; 
}