2

ファイルから特定のデータを読み取る際に問題が発生しました。このファイルの1行目と2行目は80文字で、3行目は不明な文字数です。以下は私のコードです:

int main(){
    ifstream myfile;
    char strings[80];
    myfile.open("test.txt");
    /*reads first line of file into strings*/
    cout << "Name: " << strings << endl;
    /*reads second line of file into strings*/
    cout << "Address: " << strings << endl;
    /*reads third line of file into strings*/
    cout << "Handphone: " << strings << endl;
}

コメントのアクションを実行するにはどうすればよいですか?

4

2 に答える 2

3

char strings[80]79文字しか保持できません。それを作りなさいchar strings[81]。を使用すると、サイズを完全に忘れることができますstd::string

関数を使用して行を読み取ることができますstd::getline

#include <string>

std::string strings;

/*reads first line of file into strings*/
std::getline( myfile, strings );

/*reads second line of file into strings*/
std::getline( myfile, strings );

/*reads third line of file into strings*/
std::getline( myfile, strings );

上記のコードは、1行目と2行目が80文字の長さであるという情報を無視します(行ベースのファイル形式を読んでいると想定しています)。重要な場合は、そのためのチェックを追加できます。

于 2012-12-19T13:21:57.360 に答える
1

あなたの場合、char[]よりもstringを使用する方が適切です。

#include <string>
using namespace std;

int main(){
    ifstream myfile;
    //char strings[80];
    string strings;
    myfile.open("test.txt");

    /*reads first line of file into strings*/
    getline(myfile, strings);
    cout << "Name: " << strings << endl;
    /*reads second line of file into strings*/
    getline(myfile, strings);
    cout << "Address: " << strings << endl;
    /*reads third line of file into strings*/
    getline(myfile, strings);
    cout << "Handphone: " << strings << endl;
}
于 2012-12-19T13:43:08.040 に答える