I have a text file with ten numbers only separated by spaces. I'm trying to read these values in the text file into an array in my program.
What's the best way to go about doing this? Maybe with a FOR loop? I've searched the forums and couldn't find much that was very pertinent to my problem. Some sample code would be very appreciated.
(Not really needed for my problem, but I thought I would explain what I'm trying to do. I'm trying to read files from a text file full of grades in one function, then pass it to another function to add all of the grades, then find the average of them, and then finally, in another function, write it back to another file. I don't know if it makes this any easier, but I thought I would mention it.)
Here's what I have so far. Kinda stuck...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int readFile()
{
//Declare variable
int grades[10];
char sourceFile[256];
ifstream inStream;
//Asking for user input
cout << "Source file: ";
cin >> sourceFile;
//Open file
inStream.open(sourceFile);
return grades[10];
}
for(int i = 0; i < 10 && inStream >> grades[i]; i++); is one (terrible) way to write it.
By the way, return grades[10]; returns the 11th element of array (which does not exist). You probably meant return grades;, but that's no good either. grades is a local variable, that will be gone when the function ends. You need dynamic memory here.
You mentioned that "grades" is just a local variable. I absolutely SUCK at passing parameters to functions, and even worse at passing arrays. How would I go about transferring this so that I can make it usable for the rest of my program?