Sancho Jimenez
Sancho Jimenez

Reputation: 23

Reading a string with fscanf

I was wondering how I could read a string from a file (called myFile) using fscanf. I've written this:

FILE *myFile;
string name[100];
int grade, t = 0, place = 0;

if (myFile == NULL) {
    cout << "File not found";
    return;
}

while (t != EOF) {
    t = fscanf(myFile, "%s %d\n", &name[place], &grade[place]);
    place++;
}

It gives me this error:

Error C2109 subscript requires array or pointer type on the line with fscanf I've used iostream and stdio.h

Upvotes: 1

Views: 1089

Answers (2)

MichaelGL
MichaelGL

Reputation: 61

In C++, you can use:

#include <fstream>
std::ifstream file("myFile.txt");

Assuming each line of your file is a string followed by int,as in your code,you can use something like this:

#include <iostream>
#include <fstream>

int main(){
int place =0,grade[5];
std::string name[5];
std::ifstream file("myFile.txt");

while(!file.eof()){ // end of file
 file >>name[place]>>grade[place];
place++;
}
return 0;
//Make sure you check the sizes of the buffers and if there was no error 
//at the opening of the file
}

Upvotes: 0

nicomp
nicomp

Reputation: 4647

grade is an int and you don't need the index.

t = fscanf(myFile, "%s %d\n", &name[place], &grade[place]);

should be

t = fscanf(myFile, "%s %d\n", &name[place], &grade);

Upvotes: 2

Related Questions