-
Learning C++
I just started to learn c++ and wrote a simple little calculator program, but i wanted to know what i would need to do to accept command line arguments so that it can work like this:
C:\> calc.exe 5 * 5
5 * 5 = 25
Here is the code that i got so far:
======================calc.cpp===================
Code:
#include <iostream>
int main()
{
int v1, v2, total;
char type;
std::cin >> v1 >> type >> v2;
switch ( type )
{
case '+':
total = v1 + v2;
std::cout << v1 << " + " << v2 << " = " << total << std::endl;
break;
case '-':
total = v1 - v2;
std::cout << v1 << " - " << v2 << " = " << total << std::endl;
break;
case '*':
total = v1 * v2;
std::cout << v1 << " * " << v2 << " = " << total << std::endl;
break;
case '/':
total = v1 / v2;
std::cout << v1 << " / " << v2 << " = " << total << std::endl;
break;
default:
std::cout << "Incorrect format (number * number)" << std::endl;
}
return 0;
}
==============================================
Any help is appreciated.
-
-
Here is what i got so far but it doesn't want to compile:
Code:
#include <iostream>
int main(int argc, char *argv[])
{
int total;
switch ( argv[2] )
{
case '+':
total = argv[1] + argv[3];
std::cout << argv[1] << " + " << argv[3] << " = " << total << std::endl;
break;
case '-':
total = argv[1] - argv[3];
std::cout << argv[1] << " - " << argv[3] << " = " << total << std::endl;
break;
case '*':
total = argv[1] * argv[3];
std::cout << argv[1] << " * " << argv[3] << " = " << total << std::endl;
break;
case '/':
total = argv[1] / argv[3];
std::cout << argv[1] << " / " << argv[3] << " = " << total << std::endl;
break;
*/
default:
std::cout << "Incorrect format (number * number)" << std::endl;
}
return 0;
}
Below are the compile errors that i am getting:
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
calc2.cpp:
Error E2383 calc2.cpp 12: Switch selection expression must be of integral type i
n function main(int,char * *)
Error E2085 calc2.cpp 15: Invalid pointer addition in function main(int,char * *
)
Warning W8057 calc2.cpp 41: Parameter 'argc' is never used in function main(int,
char * *)
*** 2 errors in Compile ***
-
Well each argv[n] is a \0 terminated character string.
So to test a single letter, use switch ( argv[2][0] )
> total = argv[1] + argv[3];
Being strings, you need something like strtol() or strtod() to convert from a string to an int.
-
Cool it works, thanks a lot for your help.