A lot of languages do automatic translations between types as needed. C++ is not one of them. You would call it “strictly typed”. (It is also
statically typed — which is to say, the types of things are known at compile-time, and cannot be changed while the program is running.)
So if you want something to be an integer, you must
convert it to an integer. Strings to integers is a common enough operation you get functions to do it for you. I personally prefer to use this for these kinds of things:
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <sstream>
#include <string>
#include <optional>
template <typename T>
auto string_to( const std::string & s )
{
T value;
return (std::istringstream( s ) >> value >> std::ws).eof()
? value
: std::optional <T> {};
}
| |
1 2
|
...
valm.info(string_to<int>(lvalm).value_or( 0 ), pvalm, tvalm)
| |
Unless something goes wrong, the above is roughly equivalent to:
1 2 3 4
|
#include <string>
...
valm.info(stoi(lvalm), pvalm, tvalm);
| |
The difference is that my
string_to<type>()
function will always return zero (or whatever value you specify for error) on error, where
stoi()
may throw an exception and will accept inputs like “
7abc” without complaining.
You can even catch the error and complain if you wish:
1 2 3 4 5 6 7
|
auto lvalm_optional = string_to<int>(lvalm);
if (!lvalm_optional)
{
cerr << "You must specify at least one ticket.\n";
return 1;
}
lvalm.info(*lvalm_optional, pvalm, tvalm);
| |
For homework problems I recommend you just stick with
atoi()
— unless your professor
specifically says that you must check for bad input, you can pretty safely assume that all input is good and write your code as such.
Hope this helps.