0

I have a C++ console aplication where the input parameter argv[1] should be a a string representing a decimal number in the range of uint32_t.

When the number is not in the range of uint32_t (its 0, or bigger than 4294967295), the aplication shall return error code 1.

I strugelled to find a way that works.

Any ideas?

Martin Rosenau
  • 17,897
  • 3
  • 19
  • 38
Chiller
  • 13
  • 3
  • 1
    Hard to tell what your code is doing without seeing it. Work on a [mcve]. – Retired Ninja Oct 27 '21 at 13:11
  • 1
    Typically, `argv[1]` is a `char*`, not an `uint32_t`... – Jarod42 Oct 27 '21 at 13:17
  • As retiredninja mentioned, a simple code example would go a long way. Now, considering argv[1] is a string, you can use https://en.cppreference.com/w/cpp/utility/from_chars, as it supports errors for when the string represents a number larger than an int. – diogoslima Oct 27 '21 at 13:18
  • Does this answer your question? [How to parse a string containing an integer and check if greater than a maximum in c++](https://stackoverflow.com/questions/58319823/how-to-parse-a-string-containing-an-integer-and-check-if-greater-than-a-maximum) – vsr Oct 27 '21 at 13:26

2 Answers2

0

The unsigned long type shall have at least 32 bits, so it should be able to represent any uint32_t value.

That means that you should be able to use std::strtoul to convert argv[1] and then control that unsigned long has same rank as uint_32_t or that the value is not greater that 2**32 -1.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

If I understood your question correctly, your problem is not how to write the code in C++, but how to start with the problem:

First of all, zero (0) is a valid value for uint32_t, so you only have to check if the number is larger than the maximum value but not if the number is zero.

If your program uses only digits as input, negative values are not possible (because the minus sign is not a digit).

If you use strtoul (as suggested in the other answer), you have to check errno because that function returns the maximum value (4294967295) both if this number is specified in argv[1] (which would be valid) and if a larger number is specified (which would be invalid).

If you want to write this program without using strtoul, you can also use the following approach to compare two numbers that are represented as strings:

  • Count the number of digits not including the leading zeroes.
    The number that has more digits is larger.
  • If the number of digits is the same, find the first digit that differs.
    That digit will be larger in the larger number.
    If all digits are equal, the number is equal.

This approach will also work for large numbers - for example numbers that have 100 decimal digits.

You simply have to compare the string argv[1] against the string "4294967295" this way.

Martin Rosenau
  • 17,897
  • 3
  • 19
  • 38