Basically, I'm attempting to get three things from one line of code, read from a .txt file. This will be repeated, but for now I only need to know how to get one line. The line I'm reading looks like this:
Biology $11 12
So I want to get a string, and two ints, and completely ignore the $ (note, I cannot change the .txt file, so i have to leave the $ in)
So if I have
string subject;
int biologyscores[25];
The code I have is :
int biologyscores[25]; //array to store the integer values
std::string subject; //string to store the subject the scores are for
std::ifstream infile("myScores.txt"); //declare infile to read from "myScores.txt"
infile >> subject >> biologyscores[0] >> biologyscores [1]; //read into string and int array
So the string will be used to check which subject these scores are for, and the scores themselves will be stored in an array biologyscores, indexed next to each other.
The problem is after this code executes, subject = "Biology" which is desired, but biologyscores at index 0 and 1 both seem to have junk numbers, not what I want to read into them.
CodePudding user response:
You can use a dummy character variable which will "pick up" $ character:
char dummy_char;
infile >> subject >> dummy_char >> biologyscores[0] >> biologyscores [1]; //read into string and int array
CodePudding user response:
You can use seekg and tellg
std::fstream infile("myScores.txt"); //declare infile to read from "myScores.txt"
int temp;
infile >> subject; //read into string
temp=infile.tellg(); //to get the position of $
infile.seekg(temp 1);// to move one step forward
infile>> biologyscores[0] >> biologyscores [1];//now you can read the int values