简体   繁体   中英

Reading input from a file

list.txt

first 10
second third 20
fourth fifth 30
.
.
.

What's the conventional way to read the first line separately from the others, such that I can use "first","second", ... and 10, 20, ... as their respective types elsewhere in the program?

Thanks!

Is this what you're thinking of?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM