getline seems only to read one part or it all as one string.
That makes zero sense...
You could take the C approach and use a while loop and getchar to parse the text, since each piece of information you want is separated by a comma you could just iterate through everything and divide up the pieces as you want.
Try something like that
1 2 3 4
int c;
while((c = getchar()) != myfile.eof()) {
// whatever you want...
}
#include <string>
#include <fstream>
usingnamespace std;
constint NUM_DATA = 6;
string data[NUM_DATA];
ifstream inputFile("myFile.txt");
for(int i = 0; i < NUM_DATA; i++)
{
getline( inputFile, data[i], ',' );
//do the following to discard the space after the comma
getline( inputFile, string(), ' ' );
}
inputFile.close();
//now, data[] will store everything between the commas
You can use a std::stringstream to convert from string to numerical where needed.
string record;
while (getline( f, record ))
{
istringstream ss( s );
string field;
while (getline( ss, field, ',' ))
{
// save, process, whatever with field
...
// skip any leading whitespace
ss >> ws;
}
}
So, you've got a memory access error. I wonder why. *cough* getline( foo, string(), ... ) *cough*
That just puts a space (if there is one) into a temporary string. I tried similar code and it runs fine for me (ws is the real solution, though I didn't know about that).
That said, GrameR, instead of this
getline( inputFile, string(), ' ' );
do this
inputFile >> ws;
The source of your access violation is due to going over the array bounds. If your array has 6 elements, then the valid indeces for it are 0 through 5, not 1 through 6.
Don't take this the wrong way, but so what? What you are doing is Wrong, and shouldn't work. Just because it works for you at the present time doesn't make is safe or correct.
The source of your access violation is due to going over the array bounds. ...
Nice catch! :-)
(It is hard for me to pay attention when OP refuses to use [code] blocks.)
C++ 2003 (12.2.5): A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.