2

If I'm reading in lines from a .txt file of varying length, (i.e. 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
}
}

3 Answers3

0

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>{}
    };
}
Barry
  • 286,269
  • 29
  • 621
  • 977
0

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).

Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30
  • 1
    Note that you'll not only need to check it, but reset it before the call to `strtol` you care about. Otherwise you could see an error that occurred much earlier. – Ben Voigt Oct 21 '15 at 20:13
0

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720