How to use an arguement in a function?

I have to write a code that takes two numbers and makes them into a range, then reads another number from input and if that number is defined within the range, the program ends, else it will continue asking for a new number until it's in the range.
I have tried this with an already defined range, and it worked, but now i need to define the range using two arguements, and I can't seem to figure it out.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int num(int n, int argc, char** argv) {
	int a = atoi(argv[1]);
	int b = atoi(argv[2]);
	while ((n < a) || (n > b)) {
		cout << "insert a new number: ";
		cin >> n;
	}
	return n;
}

int main(int argc, char** argv) {
	int n;
	int a = atoi(argv[1]);
	int b = atoi(argv[2]);

	cout << "insert a number: ";
	cin >> n;

	cout << num(n, a, b) << endl;
}

I think the "int argc, char** argv" should be in the int main() parenthesis, but I've tried and I don't know how to define the range in int num.
The last cout also doesn't work, and I undestand that it's because the arguements are wrong but I don't know how else to write it.
Thanks in advance.
Last edited on
Hello irene 127,

Technically int num(int n, int argc, char** argv) should work, but these variable names are better left to "main".

Consider int num(int num, int min, int max) since you already have converted "argv[1]" and "argv[2]" in main.

In "main" I would suggest:
1
2
3
int num;
int min ...
int max ...

Single letter variables are fine for "for loops", otherwise give the variables a name that means something. It will make your program easier to read and follow.

What you have look like it should work, but I have not had the chance to test it yet. When I do I will let you know.

Andy
Hello irene 127,

When I started to work on the code I first noticed:
cout << num(n, a, b) << endl;. Here you are calling the function with 3 "int"s, but the function is expecting to receive "int, int, char**".

The problem is with a prototype, function definition and function call everything has to match. It is rare when a function sends 1 variable type and the function definition changes it to a different type, i.e., sending an "int" to a function and changing it to a "double" in the function is not a problem. The reverse though would cause data loss trying to put a "double" into an "int".

In the following code I want you to notice:
The blank lines that make the code easier to read.
The function and variable names and how it makes the code easier to understand and follow.
And how the function definition now matches the function call.

Also feel free at any time to change variable names if you want. Just be sure that the name reflect what the variable is or does.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
//#include <iomanip>  // <--- Not used here.
#include <string>
#include <limits>

int CheckNum(int num, int min, int max)
{
    while ((num < min) || (num > max))
    {
        std::cerr << "\n     Your number is out of range! Try again.\n\n  insert a new number: ";
        std::cin >> num;
    }

    return num;
}

int main(int argc, char** argv)
{
    int num;
    int min = atoi(argv[1]);
    int max = atoi(argv[2]);

    std::cout << "\n Enter a number: ";
    std::cin >> num;

    std::cout << "\nYour number " << CheckNum(num, min, max) << " is within the correct range.\n";

    // <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
    // The next line may not be needed. If you have to press enter to see the prompt it is not needed.
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
    std::cout << "\n\n Press Enter to continue: ";
    std::cin.get();

    return 0;  // <--- Not required, but makes a good break point.
}


Andy
Technically int num(int n, int argc, char** argv) should work, but these variable names are better left to "main".

Actually passing argc, and argv into other functions is perfectly acceptable.

However before you try to use an argv[] past argv[0] you should really make sure they exist by examining argc. Since if they don't exist you will either be trying to use a NULL pointer or some random bit of data.

Or just
1
2
3
4
5
6
int main(int argc, char** argv) {
	int n;
	cout << "insert a number: ";
	cin >> n;
	cout << num(n, argc, argv) << endl;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>

// code that takes two numbers and makes them into a range,
// then reads another number from input and if that number is defined within the range, the program ends,
// else it will continue asking for a new number until it's in the range.

// invariant: min_value <= max_value
int get_number_in_range( int min_value, int max_value )
{
    std::cout << "enter a number in the range [ " << min_value
              << ", " << max_value << " ]: " ;

    int number ;
    if( std::cin >> number ) // if the user entered a number
    {
        // if it is in range, return it
        if( number >= min_value && number <= max_value ) return number ;

        // else continue asking for a new number until it's in the range
        std::cout << "error: that number is out of range." ; // to continue, don't return from the function
    }

    else std::cout << "error: non numeric input." ;

   // if we reach here, the input was invalid (return was not executed)
    std::cin.clear() ; // clear a possible failed state of the stream
    std::cin.ignore( 1'000, '\n' ) ; // throw the rest of the bad input line away
    std::cout << ". try again.\n" ;
    return get_number_in_range(min_value,max_value ) ; // try again
}

int main( int argc, char* argv[] )
{
    if( argc == 3 ) // right number or arguments
    {
        try
        {
            // try to convert arguments to int. this may fail (throw)
            // https://en.cppreference.com/w/cpp/string/basic_string/stol
            const int min_value = std::stoi( argv[1] ) ;
            const int max_value = std::stoi( argv[2] ) ;

            if( min_value <= max_value ) // fine, get and display a number in range
            {
                const int number = get_number_in_range( min_value, max_value ) ;
                std::cout << "you entered the number " << number << '\n' ;
            }

            else
            {
                std::cerr << "error: min value can't be greater than max_value\n" ;
                return 1 ;
            }
        }

        catch( const std::exception& ) // conversion to int failed
        {
            std::cerr << "error: the arguments can't be interpreted as int\n" ;
            return 2 ;
        }
    }

    else
    {
        std::cerr << "error: invalid number of arguments\n"
                  << "usage: " << argv[0] << " min_value max_value\n" ;
        return 3 ;
    }
} 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;

int num( int a, int b )
{
   for ( int n; ; )
   {
      cout << "Enter a number in the interval [" << a << ", " << b << "]: ";
      cin >> n;
      if ( n >= a && n <= b ) return n;
      cout << "Out of range. Try again.\n\n";
   }
}

int main( int argc, char** argv )
{
   int a = atoi( argv[1] );
   int b = atoi( argv[2] );
   if ( a > b ) swap( a, b );
   int n = num( a, b );
   cout << "Valid number is " << n << '\n';
}

Last edited on
I finally understood! It was such a simple solution yet I couldn't manage to find it... Thank you all for your help! much appreciated ^^
Topic archived. No new replies allowed.