【问题标题】:File IO reading multiple types from a file文件 IO 从文件中读取多种类型
【发布时间】:2012-12-12 18:52:38
【问题描述】:

假设我有一个这样的文本文件

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;
}

【问题讨论】:

  • 你能分享一些你的代码sn-p吗?这将有助于了解需要改进的地方。
  • 您可以随时阅读所有内容,然后将您不想要的内容分开。
  • 你唯一的问题是第一次。保持 myFile>>x>>y;并失去它周围的时间。

标签: c++ parsing file-io io


【解决方案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;
}

【讨论】:

    【解决方案2】:

    如果您使用 fstream,只需调用 ignore() 方法:

    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);
    

    【讨论】:

      【解决方案3】:

      试试这样的:

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        相关资源
        最近更新 更多