2017-12-11 27 views
1

fscanfを使用してファイル(myFile)から文字列を読み取る方法が不思議でした。私はこれを書いている:fscanfで文字列を読み取る

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の添字は、私がのiostreamとstdio.hの

+1

C IO関数はわかりませんC++クラス( 'name')と' grade'に関するものは配列ではありません。 – crashmstr

+0

代わりにC++ I/Oを使用してください。 – molbdnilo

+0

同じ効果が必要な場合は、iostreamだけを使ってcppで何を使うことができますか? –

答えて

2

を使用しましたfscanfは と行に配列やポインタ型が必要ですグレードはintでインデックスは必要ありません。

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

はC++で

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

しかし、実際には 'std :: string'では動作しません。 – molbdnilo

+1

char * name [100]を使用して –

+0

私は悪いグレード[100]でした。コードを間違ってコピーしている必要があります。 –

0

する必要があり、あなたが使用することができます。

#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 
} 
関連する問題