开发者

Advance File Pointer to skip over number in a file

I was wondering If I could jump positions in a text file. Suppose I have this file.

12
8764
2147483648
2
-1

Whenever I try to read the third number it won't read because its larger than the max number for a 32 bit int.So whenever i reach the third number, it keeps reading the second over and over again. How can I jump to the 4th nu开发者_StackOverflowmber?


Use std::getline instead of operator>>(std::istream, int)

std::istream infile(stuff);
std::string line;
while(std::getline(infile, line)) {
    int result;
    result = atoi(line.c_str());
    if (result)
        std::cout << result;
}

The reason you are experiencing the behavior that you are, is that when the std::istream tries (and fails) to read in an integer, it sets a "badbit" flag which means that something went wrong. As long as that badbit flag remains set, it won't do anything at all. So it's not actually re-reading in that line, it's doing NOTHING, and leaving the value that had been there alone. If you want to keep more in line with what you already had, it's probably like below. The above code is simpler and less error prone though.

std::istream infile(stuff);
int result;
infile >> result; //read first line
while (infile.eof() == false) { //until end of file
    if (infile.good()) { //make sure we actually read something
        std::cout << result;
    } else 
        infile.clear(); //if not, reset the flag, which should hopefully 
                        // skip the problem.  NOTE: if the number is REALLY
                        // big, you may read in the second half of the 
                        // number as the next line!
    infile >> result; //read next line
}


You can first read the line, then convert the line to integer if you can. Here is an example for your file :

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main()
{
    std::ifstream in("file");
    std::string line;
    while (std::getline(in, line)) {
        int  value;
        std::istringstream iss(line);
        if (!(iss >> value)) {
            std::istringstream iss(line);
            unsigned int uvalue;
            if (iss >> uvalue)
                std::cout << uvalue << std::endl;
            else
                std::cout << "Unable to get an integer from this" << std::endl;
        }
        else
            std::cout << value << std::endl;
    }
}


As an alternative to using std::getline(), you could call std::ios::clear(). Consider this excerpt from your previous question

    fin >> InputNum;

You could replace that code with this:

    fin >> InputNum;
    if(!fin)
        fin.clear();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜