简体   繁体   中英

How to detect you've reached the end of a fgets string of integers, when 0 is the last integer in the line, using c++?

If I'm reading in lines from a .txt file of varying length, (ie 5 integers on line 1, then 2 integers on line 2, then 10 integers on line 3, and etc.), using fgets (although I don't necessarily need to use it, just seemed like a good tool in my situation). Every solution I find returns an error of 0 (like strtol or atio).

char str[100];
char* p = str;
FILE* fp;
fp = open("text.txt",r);
if(fp == NULL) 
    printf("aborting.. Cannot open file! \n");
while(!foef(fp))
{
if(fgets(p,100,fp) != NULL)
{
    for (int j = 0 ; j < 20 ; j+=2) 
    {
        temp1 = strtol(p, &p, 10);
        // need to store temp1 into arr[j] if it is a valid integer (0->inf)
        // but should discard if we are at the end of the line
}
}

You could actually use C++:

std::ifstream file("text.txt");
std::string line;
while (std::getline(file, line)) {
    std::istringstream iss(line);
    int i;
    while (iss >> i) {
        // ...
    }
}

The inner loop could simply load all of the ints into a vector directly or something:

std::ifstream file("text.txt");
std::string line;
while (std::getline(file, line)) {
    std::istringstream iss(line);
    std::vector<int> all_the_ints{
        std::istream_iterator<int>{iss},
        std::istream_iterator<int>{}
    };
}

Ben's answer was so good, it should be part of the answer

Set errno to 0 before calling strtol.

Check errno. From man page

ERANGE

The resulting value was out of range. The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned) .

You're throwing away the information available from strtol .

In particular, after a call

val = strtol(p, &endp, radix);

you are interested in whether p == endp .

In your call strtol(p, &p, radix) you're overwriting p too soon and losing the chance to perform the test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM