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 전에 모든 것을 읽었지만 일단 해당 라인에 도달하면 아무것도하지 않습니다. 누구든지 내가 뭘 잘못하고 있는지 말해 줄 수 있습니까? 이 작업을 수행하는 방법에 대한 더 나은 제안이 있습니까 ???
나는 본질적으로 파일을 거쳐 당시에 하나의 "단어"(흰색 문자가 아닌)를 가야합니다. 나
감사
해결책
'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