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

问题评论:

1  
C IO functions don’t know anything about C++ classes (name) and grade is not an array.
    
Use C++ I/O instead.
    
What could I use in cpp using only iostream if I want the same effect?
– Sancho Jimenez
2 hours ago

答案:

答案1:

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);

答案评论:

    
Doesn’t really work with std::string, though.
1  
Use char *name[100] then
    
oops my bad that should have been grade[100]. Must have made a mistake copying over the code.
– Sancho Jimenez
2 hours ago

答案2:

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
}

答案评论:

原文地址:

https://stackoverflow.com/questions/47753489/reading-a-string-with-fscanf

Tags:

添加评论