를 사용하여 표준 : :의 getline >> (표준 : : IStream을, int)를
std::istream infile(stuff);
std::string line;
while(std::getline(infile, line)) {
int result;
result = atoi(line.c_str());
if (result)
std::cout << result;
}
이유 당신이, 당신이 행동을 경험하고는 그 때 표준 :: istream로의 시도 (실패 할 경우) 정수로 읽으려는 경우 "badbit"플래그가 설정되어 무언가 잘못되었음을 의미합니다. 해당 badbit 플래그가 설정된 상태로 있으면 아무 것도 수행하지 않습니다. 따라서 실제로는 그 라인에서 다시 읽지 않습니다. 아무 것도하지 않고 홀로 존재했던 가치를 떠납니다. 당신이 이미 가지고 있던 것과 더 많은 것을 맞추고 싶다면, 그것은 아마도 아래와 같습니다. 위의 코드는 더 간단하고 오류가 발생하기 쉽습니다.
std::istream infile(stuff);
int result;
infile >> result; //read first line
while (infile.eof() == false) { //until end of file
if (infile.good()) { //make sure we actually read something
std::cout << result;
} else
infile.clear(); //if not, reset the flag, which should hopefully
// skip the problem. NOTE: if the number is REALLY
// big, you may read in the second half of the
// number as the next line!
infile >> result; //read next line
}
인가? –