Re: fstream problem
On Nov 12, 9:04 am, "beepa" <sil...@shhh.com> wrote:
As you will be able to see I am fairly new at this. Here is the part I'm
having problems figuring out:
The file I'm inputing from is formated like this:
firstName lastName
postion name (one or two words)
firstName lastName
first base (for example)
firstName lastName
position name (one or two words)
I'm trying to seperate the first name from the last name
putting the last name in parallel arrays with the position in
the other array.
I'm not too sure what you mean by "parallel arrays", but if I
understand you correctly, each record in the file consists of
two lines. With the first name and the last name on the first
line, and the position on the second.
The garbage array I set up just to see what I was getting rid
of. When the position has two words it always gets messed up
as far as what it puts in the arrays the code is runable. Any
suggestions would be most welcome. TIA (This is just a C++
win32console program created in an empty solution using MS
Visual Studio 2005)
[code]
#include <iostream>
#include <fstream>
#include <string>
If you're going to have arrays, you'll need
#include <vector>
as well.
using namespace std;
int main()
{
char sentry;
string garbage[9];
string player[9];
string position[9];
fstream inFile;
inFile.open("team1.txt");
You should check that the open succeeded.
for(int test = 0; test < 9; test++)
{
inFile >> garbage[test];
inFile >> player[test];
getline(inFile,position[test]);
OK. First, >> to a string doesn't extract trailing "white
space", so the '\n' character which terminates the first line is
left in the stream. The getline then reads up to that
character. Which isn't what you want.
Personally, I'd do this a bit different:
struct Entry
{
std::string garbage ;
std::string player ;
std::string position ;
} ;
std::vector< Entry >array ;
std::string line1 ;
std::string line2 ;
while ( std::getline( inFile, line1 )
&& std::getline( inFile, line2 ) ) {
Entry e ;
std::istringstream s( line1 ) ;
s >> e.garbage >> e.player ;
e.position = line2 ;
array.push_back( e ) ;
}
But with a lot more error handling, in case the file was
corrupt. (I'd also probably allow spaces in the last name. In
anything less trivial, of course, Entry would be a class with a
constructor and a >> operator.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34