从文件中读取输入

时间:2012-10-18 05:12:17

标签: c++

LIST.TXT

first 10
second third 20
fourth fifth 30
.
.
.

将第一行与其他行分开阅读的常规方法是什么,这样我可以使用“第一”,“第二”,......和10,20,...作为程序中其他地方的各自类型?

谢谢!

2 个答案:

答案 0 :(得分:3)

这是你在想什么?

ifstream fin("list.txt");

string str1, str2;
int n;

fin >> str1 >> n; // first 10

// do something with "first" and 10

while(fin >> str1 >> str2 >> n)
{
  // do something with str1, str2 and n
}

答案 1 :(得分:0)

struct header { 
    std::string name;
    int number;
};

std::istream &operator>>(std::istream &is, header &h) { 
    return is >> h.name >> h.number;
}

struct line { 
    std::string first;
    std::string second;
    int number;
};

std::istream &operator>>(std::istream &is, line &data) { 
    returns is >> data.first >> data.second >> data.number;
}

int main() { 
    header h;
    std::ifstream data("list.txt");

   // read first line:
   data >> h;
   // now h.name and h.number are the string and number from the first line

   // read the rest of the lines:
   std::vector<line> lines((std::istream_iterator<line>(data),
                            std::istream_iterator<line>());

   // now lines[i].first, lines[i].second and lines[i].number
   // are the first string, second string, and number
   // from the i-th line of three-field data from the file.

   return 0;
}