Error Reading string from a file using Getline

So i have a file:
3 Electric Hammer# 20

I am using these lines of code to read in the data, i get an error once i step into the getline saying "Error reading characters of string"

M question is why? any suggestions?
1
2
3
4
5
6
7
8
9
10
11
             /*  struct record {   //This is the struct data if that is helpful
	           int number;
	           string toolName[20];
	           int quantity;
	           double cost;
};  */


                infile >> box[i].number;
		getline(infile, box[i].toolName[20], '#');
		infile >> box[i].quantity;
Last edited on
Try this on line 10:

1
2
3

getline( infile, box[ i ].toolName, '#' );
if i do that I get an error on line 10:
Error (active) no instance of overloaded function "getline" matches the argument list
Last edited on
In the struct, does the string toolName need to be an array or just a single string?

In any case, the original code was attempting to access an out-of-bounds element.


Last edited on
it needs to be a array to gather the spaces between the words
Chervil...i do not see why it is access an out of bounds element, the cursor should be right after 3 then once i use getline it should take an data into the string array until it reaches the delimiter...that was my basic understanding how getline works..so could you show me code explaining what is the correct way?

i.e if i use a char array i get a ton of errors, which would make more sense to me
Last edited on
The out of bounds error was caused by trying to modify the 21st element in an array of 20 strings.
 
    getline(infile, box[i].toolName[20], '#');

valid subscripts would be in the range 0 to 19.

it needs to be a array to gather the spaces between the words

But a string can contain more than one word separated by spaces.

I think you are getting confused between the idea of an array of characters, which can hold a string, and the C++ std::string which does the same task.

I'd suggest changing the struct - see if this makes sense:
1
2
3
4
5
6
struct record {  
    int number;
    string toolName;
    int quantity;
    double cost;
}; 


1
2
3
    infile >> box[i].number >> ws;  // skip any trailing whitespace
    getline(infile, box[i].toolName, '#');
    infile >> box[i].quantity;
Last edited on
Thanks that worked!

curious so for my original code to work my spacing in my file being read in had to be flawless?

or i should have had an :
getline(infile, box[i].toolName[19], '#');
I don't think the spacing in the file would make much difference.

This would have been valid code, but it was clearly wasteful as the other elements would remain unused.
getline(infile, box[i].toolName[19], '#');

As for the use of a toolName array in this situation it could possibly make sense if the item had several different names, which from the sample data appeared unlikely.
Topic archived. No new replies allowed.