Reading in City names from file

hello, I'm trying to understand the best way to read in a city name from file when the file looks like this:

s New York 23 14 1
s Miami 25 25 25

a char, string, and three numbers.
I've tried a couple things like,

 
  file >> char1 >> string1 >> num1 >> num2 >> num3;

that gives only the New of New York and 0 for the numbers.
also i've tried this

1
2
3
    file >> card;
    getline(file,tempCity," ");
    file >> amt1 >> amt2 >> amt3;

still no luck when printed.

What is the right way to do this?
The problem you have is that there is no way to find the end of the city name. cin will stop at the first white space char so file >> char1 >> string1 >> num1 >> num2 >> num3; it will stop after New then tries to read York into num1 which of course fails.

Best way would be to terminate the city name with a ',' or ';'
s New York, 23 14 1
s Miami, 25 25 25

then you can read the city with getline.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;


//======================================================================


string trim( string s )                          // Remove leading and trailing blanks
{
   int i = s.find_first_not_of( " " );
   if ( i == string::npos ) return "";

   int j = s.find_last_not_of( " " );
   return s.substr( i, j - i + 1 );
}


//======================================================================


int main()
{
   string digits = "0123456789";
   string line, city, rest;
   char c;
   vector<int> numbers;

   stringstream fakeFile( "s New York 23 14 1\ns Miami 25 25 25" );      // replace with a file once working

   while ( fakeFile >> c && getline( fakeFile, line ) )  // read first character, then the rest of the line
   {
      int pos = line.find_first_of( digits );    // index of first number
      city = line.substr( 0, pos );              // first part is the city name
      city = trim( city );                       // remove leading and trailing blanks
      rest = line.substr( pos );                 // second part contains the numbers

      stringstream ss( rest );                   // put second part into a new stream
      numbers.clear();                           // remove any previous content
      int n;
      while ( ss >> n ) numbers.push_back( n );  // stream the numbers into the array

      // Check what you have got
      cout << "\nLine content is:\n";
      cout << "   Character: " << c << '\n';
      cout << "   City: " << city << '\n';
      cout << "   Numbers: ";
      for ( int i : numbers ) cout << i << " ";
      cout << '\n';
   }
}


Line content is:
   Character: s
   City: New York
   Numbers: 23 14 1 

Line content is:
   Character: s
   City: Miami
   Numbers: 25 25 25 

Last edited on
Ok thank you both
Topic archived. No new replies allowed.