paramFile >> tmp;
行にスペースが含まれている場合、これは行全体を読み取りません。std::getline(paramFile, tmp);
改行まで読み取るその使用が必要な場合。基本的なエラーチェックは、戻り値を調べることによって行われます。例えば:
if(paramFile>>tmp) // or if(std::getline(paramFile, tmp))
{
std::cout << "Successful!";
}
else
{
std::cout << "fail";
}
operator>>
両方ともstd::getline
ストリームへの参照を返します。ストリームはブール値に評価され、読み取り操作後に確認できます。上記の例は、読み取りが成功した場合にのみtrueと評価されます。
これが私があなたのコードを作る方法の例です:
ifstream paramFile("somefile.txt"); // Use the constructor rather than `open`
if (paramFile) // Verify that the file was open successfully
{
string tmp; // Construct a string to hold the line
while(std::getline(paramFile, tmp)) // Read file line by line
{
// Read was successful so do something with the line
}
}
else
{
cerr << "File could not be opened!\n"; // Report error
cerr << "Error code: " << strerror(errno); // Get some info as to why
}