ifstreamを使用したファイルの読み取り
質問
ファイルから読み取ろうとしています: ファイルは複数行であり、基本的に各「単語」を調べる必要があります。言葉は何でもスペースではない。
サンプル入力ファイルは次のようになります:
サンプルファイル:
テスト2d
ワード3.5
入力
{
テスト13.5 12.3
別の{
テスト145.4
}
}
だから私はこのようなことを試みました:
ifstream inFile(fajl.c_str(), ifstream::in);
if(!inFile)
{
cout << "Cannot open " << fajl << endl;
exit(0);
}
string curr_str;
char curr_ch;
int curr_int;
float curr_float;
cout << "HERE\n";
inFile >> curr_str;
cout << "Read " << curr_str << endl;
問題は、新しい行を読み取るときにハングすることです。テスト13.5の前にすべてを読みました しかし、その行に到達すると、何もしません。 誰が私が間違っているのか教えてもらえますか? これを行う方法についてのより良い提案???
基本的にファイルを調べて、「単語」を1つ書く必要があります(非白い文字)その時。 私は
ありがとう
解決
ファイル「inFile」を開きましたが、「std :: cin」から特定の理由を読み取っていますか?
/*
* Open the file.
*/
std::ifstream inFile(fajl.c_str()); // use input file stream don't.
// Then you don't need explicitly specify
// that input flag in second parameter
if (!inFile) // Test for error.
{
std::cerr << "Error opening file:\n";
exit(1);
}
std::string word;
while(inFile >> word) // while reading a word succeeds. Note >> operator with string
{ // Will read 1 space separated word.
std::cout << "Word(" << word << ")\n";
}
他のヒント
どのように「精神の内」がわからないのかこれはiostreamライブラリの例ですが、フォーマットされていない入力でも可能です。次のようなもの:
char tempCharacter;
std::string currentWord;
while (file.get(tempCharacter))
{
if (tempCharacter == '\t' || tempCharacter == '\n' || tempCharacter == '\r' || tempCharacter == ' ')
{
std::cout << "Current Word: " << currentWord << std::endl;
currentWord.clear();
continue;
}
currentWord.push_back(tempCharacter);
}
それは機能しますか?
所属していません StackOverflow