开发者

Reading through file using ifstream

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 wou开发者_JAVA百科ld 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


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";
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜