Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ read string with spaces

Tags:

c++

istream

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 ?

like image 974
Simon Avatar asked Jun 19 '26 15:06

Simon


1 Answers

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();
like image 140
Drew Dormann Avatar answered Jun 21 '26 03:06

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!