1

I have a text file that I want to read using C. It contains lines in this format: %d %d (%d or %lf). An example of 3 lines:

1 0 44
2 0 84.13
3 1 15.07

But the last number can be either int or double, arbitrary. How can I read from the text file regardless of the data type?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
CVaida
  • 53
  • 4
  • check if the last number contains a dot, maybe – moffeltje May 19 '15 at 20:17
  • 1
    Why does it matter? (Seriously. Any integer can be read as a floating point value, and -- at least on x86 hardware -- any `int` can be represented precisely as a `double`. So it is not necessary to avoid losing information. Without knowing why it is important, it is hard to construct a useful answer.) – rici May 20 '15 at 00:50
  • 1
    If you read a line-at-a-time with `fgets` or the like, you can then use `strtol` to read `intpart` on all values and check the updated `*endptr == '.'` to determine if the value was actually a float. If the test is true, then read with `p = endptr; floatpart = strtof (p, &endptr); floatvar = (float)(intpart)+floatpart` (in fact you can parse each line that same way and only reading a floatpart if the `*endptr == '.'` tests true after each `intpart` read). – David C. Rankin May 21 '15 at 09:34

1 Answers1

1

Since float can hold an integer but not vice versa. Just read the data like a float and check if it is an integer using something like

if(ceilf(f) == f)
{
  i=(int)f;
}
//Here i is an integer and f is the float you read using %f

To see more methods on how to check if a float is int see

Checking if float is an integer

Community
  • 1
  • 1
dev_ankit
  • 516
  • 4
  • 8
  • The test `ceilf(f) == f` checks whether `f` is an integer, but not whether it is representable as an `int`. For example, 2.0E100 is an integer. – rici May 20 '15 at 00:48
  • you can always go to long, long long, etc. the problem here is to check if there is a decimal or not – dev_ankit May 20 '15 at 02:28
  • 1
    2.0E100 has a decimal, and it is certainly not a valid `%d` as per the OP. But your test will report that it is an integer. I don't see why you would just assume that to be correct given the wording of the question. I didn't find the OP sufficiently clear to make a precise determination, though. – rici May 20 '15 at 02:34