Reading from file, strings.

I am in the process of adding a string to an array, followed by a line with four integers. I can get them to all enter into the arrays and they output correctly... almost. The strings are cut-off after the first whitespace. As a result they do not display properly.

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
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
#include <string>

int numcities = 744;

int main ()
{
  int northdegree[numcities], northminute[numcities], westdegree[numcities], westminute[numcities];
  int integer;
  string name[numcities], line;
  for (int i = 0; i < numcities; i++)
  {
	northdegree[i] = 0;
	northminute[i] = 0;
	westdegree[i] = 0;
	westminute[i] = 0;
	name[i] = " ";
  }
  ifstream in ("Cities N W Degrees Minutes.txt");
  int counter = 0;
  while (!in.eof() && counter < numcities)
  {
	getline(in, line);
	istringstream ss(line);
	ss >> name[counter];
	
	getline(in, line);
	istringstream tt(line);
	
	tt >> northdegree[counter] >> northminute[counter] >> westdegree[counter] >> westminute[counter];
	cout << name[counter] << " " << northdegree[counter] << " " << northminute[counter] << " "
							<< westdegree[counter] << " " << westminute[counter] << " ";
	counter++;
  }
  in.close();
  return 0;
}


Example:
Output from my program:
Sumter, 33 54 80 22

Text file:
Sumter, Shaw AFB
33 54 80 22

Another thing. I tried simply doing getline(in, line) then line = name[counter] and that... gave me nothing as output.
Last edited on
The >> operator stops reading as soon it encounters a space character.
By doing ss >> name[counter]; you only get the first word of ss.
To correct that you must do
1
2
3
getline(in, line);
istringstream ss(line);
name[counter] = ss.str();

or even better
 
getline(in, name[counter] );
I attempted both of these.
Both gave me a similar output, just the 4 numbers on the last line of the text file. So I'm unsure what to do.
Modifying the output a bit it just doesn't give anything for the name array.

Edit: I decided that, due to time constraints, I would replace all spaces in the middle of the names with periods. I'm still curious how to fix this though.
Last edited on
I tested your program with the modifications I suggested, and it works perfectly.

I think the only reason it can fail is if there are empty lines before what you want to read.
Taking that into account, here is a code that should work:
1
2
3
in >> name[counter]; // skips empty lines and blank characters until it finds a word
getline(in, line); // get the remainder of the line
name[counter] += line; // concatenate both strings 
Last edited on
Topic archived. No new replies allowed.