2

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 ?

Simon
  • 242
  • 2
  • 3
  • 13

4 Answers4

3

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();
Johnny Mnemonic
  • 3,424
  • 4
  • 18
  • 31
3

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();
Drew Dormann
  • 50,103
  • 11
  • 109
  • 162
  • thank you for response, shouldn't be the same change inside the while too ? – Simon Apr 14 '13 at 18:46
  • @Simon YES! Thanks for catching that. Note that I simplified the code as well. An `istream` can be used alone in [a bool context](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) – Drew Dormann Apr 14 '13 at 18:47
  • Thank you, do i need also to change char city[100] to a string city; ? – Simon Apr 14 '13 at 18:51
  • @Simon while you don't *need* to, there are many protections that a `std::string` offer that an array won't. In that case, you would want `std::getline( f, city );` – Drew Dormann Apr 14 '13 at 18:52
1

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

1

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.

Community
  • 1
  • 1
john
  • 71,156
  • 4
  • 49
  • 68