views:

282

answers:

2

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

+1  A: 

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";
}
Martin York
typo :)i meant to say inFile >> in question not program itself
grobartn
A: 

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), !file.eof())
{
 if (tempCharacter == L'\t' || tempCharacter == L'\n' || tempCharacter == L'\r' || tempCharacter == L' ')
 {
  std::cout << "Current Word: " << currentWord << std::endl;
  currentWord.clear();
  continue;
 }
 currentWord.push_back(tempCharacter);
}

Does that work?

Billy ONeal