0

I am trying to read a line from a file that has spaces in it. Despite everything I've tried and all my research, nothing seems to work, here is my current attemp

void read_name(fstream& in_file, comp& cmp)
{
   char buff[80];
   in_file.getline(buff, 79, '\n');
   in_file >> buff;

   cout << "NAME: " << buff << endl;

   cmp.set_name(buff);
   in_file.getline(buff, 79);
}

For whatever reason, this will still read until it sees a space and then stops. Any help would be much appreciated. I'm not that great with straight C++ so I could very well just be missing something.

4

3 に答える 3

1
in_file.getline(buff, 79, '\n');

そこには。行を読みます (行が 78 文字以内であると仮定します)。それで、なぜあなたは行ってこれをしたのですか?

in_file >> buff;

これにより、今読んだ行が次の単語で上書きされます。次の行が必要な場合は、getline を再度呼び出します。

ただしstd::string、 free 関数を使用すると、std::getline行の長さを指定する必要がなくなります。

std::string buff;
std::getline(in_file, buff);
于 2013-03-22T18:57:04.410 に答える
1

この線

in_file >> buff;

ファイルから読み取ったばかりの buff の内容を消去しています。buff の内容を監視しているデバッガーを使用してコードをステップ実行すると、これが発生することがわかります。

于 2013-03-22T18:58:40.783 に答える
0

C++ を使用しているため、char 配列の代わりに stl 文字列を使用することをお勧めします。

std::string linestr;
while( std::getline(input, linestr) )
{
   // process line
}

入力はifstreamです。

于 2013-03-22T18:53:29.827 に答える