3

I am trying to read from file: The file is multiline and basically i need to go over each "word". Word being anything non space.

Sample input file would be:

Sample file:

test 2d
word 3.5
input
{

test 13.5 12.3
another {
testing 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 when it reads new line it just hangs. I read everything before test 13.5 but once it reaches that line it doesnt do anything. Anyone can tell me what I am doing wrong? Any better suggestion on how to do this???

I essentially need to go through file and go one "word" (non white char) at the time. I

Thanks

2 Answers 2

3

You open a file 'inFile' but are reading from the 'std::cin' any particular 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"; } 
Sign up to request clarification or add additional context in comments.

1 Comment

typo :) i meant to say inFile >> in question not program itself
1

Not sure how "in the spirit" of the iostream library this is, but you could 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); } 

Does that work?

2 Comments

That won't work because istream::get doesn't take a single char* as parameter and checking !file.eof() before performing a read doesn't always work. Also, you're comparing wide character literals to a narrow object of type char (those types are not compatible). I will edit it for you to get it fixed.
@0x499602D2: Thanks for fixing that up :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.