Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active December 13, 2023 23:16
Show Gist options
  • Save mshafae/d8488f24f51eaf25e2213d5091927253 to your computer and use it in GitHub Desktop.
Save mshafae/d8488f24f51eaf25e2213d5091927253 to your computer and use it in GitHub Desktop.
CPSC 120 working with stoi and stof
// Gist https://gist.github.com/d8488f24f51eaf25e2213d5091927253
#include <iostream>
#include <vector>
#include <string>
int main(int argc, char const *argv[]) {
std::vector<std::string> arguments = std::vector<std::string>(argv, argv + argc);
for(const std::string& arg : arguments){
try{
int an_integer = std::stoi(arg);
std::cout << "\"" << arg << "\" can be converted to an integer!\n";
std::cout << an_integer << " / 2 = " << an_integer / 2 << "\n";
}catch(std::exception const& e){
std::cout << "Looks like \"" << arg << "\" isn't an integer because stoi() couldn't make sense of it.\n";
}
try{
float a_float = std::stof(arg);
std::cout << "\"" << arg << "\" can be converted to a float!\n";
std::cout << a_float << " / 2.0 = " << a_float / 2.0 << "\n";
}catch(std::exception const& e){
std::cout << "Looks like \"" << arg << "\" isn't a float because stof() couldn't make sense of it.\n";
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment