logi c должен go что-то вроде,
Read a line.
If read succeeded
If line not empty
Provide line
Else
Try again
Else
Handle error
Переводя это в код и объединяя его в функцию для удобного повторного использования, мы получаем
std::string getNotEmptyLine(std::istream & in)
{
while (true) // repeat forever!
{
std::string temp;
std::getline(in, temp); // get a line
if (in) // test the line
{
if (line.size() != 0) // line not empty
{
return temp; //give it to caller
}
}
else
{
// handle error. We'll throw an exception, but this isn't the best solution
throw std::runtime_error("Couldn't read a line!");
}
}
}
Как и со всеми дословными переводами, над этим нужно немного поработать. Также было бы полезно, чтобы эта функция работала точно так же, как getline
, чтобы вызывающий абонент мог использовать ее в качестве замены.
std::istream & getNotEmptyLine(std::istream & in, // stream to read
std::string & line, // somewhere to put the string
char delim = '\n') // allow different delimiters
{
while (true) // repeat forever!
{
if (std::getline(in, line, delim)) // get a line right in line and test that we got it.
{
if (line.size() != 0) // line not empty
{
break; // success. exit.
}
}
else
{
// line will contain whatever this implementation of `getline` puts or
// leaves in the string on failure.
break; // fail. Let the caller decide what to do
}
}
return in;
}
Использование:
Info info;
std::string aLine;
if (getNotEmptyLine(in, info.animalchicken) &&
getNotEmptyLine(in, info.animaldog) &&
getNotEmptyLine(in, info.car) &&
getNotEmptyLine(in, aLine))
{
info.number = std::stoi(aLine);
}
else
{
// handle error
}
Примечание. даже это может быть слишком упрощенно c. Он не может обрабатывать строку, содержащую только пробелы. Единичное неуместное и почти невидимое пространство нанесет ущерб хаво c. Если это вызывает беспокойство, добавьте еще logi c к if (line.size() != 0)
.