Reading through a file using ifstream
I am trying to read from a file: The file is multi-line and basically I need to go through each "word". The word is something not a cosmos.
Sample input file:
Example file:
test 2d
word 3.5
input
{
test 13.5 12.3
other {
test 145.4
}
}
So, I tried something like this:
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;
The problem is that when reading a new line, it just hangs. I read everything before challenge 13.5 but once it reaches this line it does nothing. Can anyone tell me what I am doing wrong? Any better suggestion on how to do this ???
I essentially need to go through the file and go to one "word" (not white char) at a time. I
thank
source to share
Are you opening the file 'inFile' but reading from "std :: cin" for any specific reason?
/*
* 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";
}
source to share
Not sure how this is "in the spirit" of the iostream library, but you can do it with unformatted input. Something like:
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);
}
It works?
source to share