简体   繁体   中英

C++ read string with spaces

I have file like this:

59 137 New York
137 362 Syracuse
216 131 New Jersey
...
..
.

and I would like to read it to a structure: X - Y - name of a city

  char city[100];
  int x , y;
  f.open("map.txt");
  f >> x >> y >> city;
  while (!f.fail()) {
    f >> x >> y >> city;
  }
  f.close();

Problem is, that city reads only until next space, so from New York it reads only New. How should I read whole rest of a line, in some easy and smart way ?

You can do something like this:

  f.open("map.txt");
  string city;
  int x , y;
  f >> x >> y;
  getline(f,city);

  while (!f.fail()) {
  f >> x >> y;
  getline(f,city);
  }
  f.close();

The format of your file seems to imply that the name of the city ends at the end of a line , not a space .

You can read that form using getline

  char city[100];
  int x , y;
  f.open("map.txt");
  while ( f ) {
      f >> x >> y;         
      f.getline(city, 100); 
  }
  f.close();

Use getline(f, city) for city. So, you have f >> x >> y; getline(f, city);

This code reads spaces and handles end of file correctly. None of the other answers do this I think

while ((f >> x >> y).getline(city, 100))
{
}

See this for more information on how to correctly test for end of file.

Of course you should be doing things the easy way using std::string as others have said.

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