用fscanf读取字符串

时间:2017-12-11 12:55:51

标签: c++

我想知道如何使用fscanf从文件(称为myFile)中读取字符串。我写过:

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++;
}

它给了我这个错误:

错误C2109下标需要fscanf行上的数组或指针类型 我使用过iostream和stdio.h

2 个答案:

答案 0 :(得分:2)

成绩是一个整数,你不需要索引。

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

应该是

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

答案 1 :(得分:0)

在C ++中,您可以使用:

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

假设你文件的每一行都是一个后跟int的字符串,就像你的代码一样,你可以使用这样的东西:

#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
}