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
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
usingnamespace 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