用fscanf读取字符串

Reading a string with fscanf

本文关键字:字符串 读取 fscanf      更新时间:2023-10-16

我想知道如何使用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 %dn", &name[place], &grade[place]);
    place++;
}

它给了我这个错误:

错误c2109下标要求使用FSCANF在行上的数组或指针类型我已经使用了iostream和stdio.h

等级是int,您不需要索引。

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

应该是

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

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