1

コードは次のとおりです。

コード:

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
    int id;
    char name[50];
    ifstream myfile("savingaccount.txt");  //open the file
    myfile >> id;

    myfile.getline(name , 255 , '\n');   //read name **second line of the file
    cout << id ;
    cout << "\n" << name << endl; //Error part : only print out partial name 
    return 0;
}

ファイルの内容:

1800567
Ho Rui Jang
21
女性
マレーシア人
012-4998192
20 , Lorong 13 , Taman Patani Janam
Melaka
Sungai Dulong

問題 :

1.) getline が名前を char 配列 name に読み込み、名前を出力できることを期待しています。完全な名前を取得するのではなく、名前の一部しか取得しないのですが、なぜこのようなことが起こるのでしょうか?

ありがとうございました!

4

1 に答える 1

2

問題は、最初の行の末尾にあるmyfile >> id改行 ( ) を消費しないことです。\nしたがって、呼び出すgetlineと、ID の末尾からその行の末尾まで読み取られ、空の文字列が取得されます。もう一度呼び出すgetlineと、実際に名前が返されます。

std::string name; // By using std::getline() you can use std::string
                  // instead of a char array

myfile >> id;
std::getline(myfile, name); // this one will be empty
std::getline(myfile, name); // this one will contain the name

私のアドバイスはstd::getline、すべての行に使用することです。行に数値が含まれている場合は、std::stoi(コンパイラが C++11 をサポートしている場合) またはboost::lexical_cast.

于 2012-09-03T16:59:54.507 に答える