Jak przekonwertować argument wiersza poleceń na int?
Muszę uzyskać argument i przekonwertować go na int. Oto Mój kod do tej pory:
#include <iostream>
using namespace std;
int main(int argc,int argvx[]) {
int i=1;
int answer = 23;
int temp;
// decode arguments
if(argc < 2) {
printf("You must provide at least one argument\n");
exit(0);
}
// Convert it to an int here
}
7 answers
ponieważ ta odpowiedź została jakoś zaakceptowana i tym samym pojawi się na górze, chociaż nie jest najlepsza, poprawiłem ją na podstawie innych odpowiedzi i komentarzy.
Sposób C; najprostszy, ale potraktuje dowolną niepoprawną liczbę jako 0:
#include <cstdlib>
int x = atoi(argv[1]);
Sposób C z sprawdzaniem wejścia:
#include <cstdlib>
errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
std::cerr << "Number out of range: " << argv[1] << '\n';
}
Sposób C++ iostreams z sprawdzaniem wejścia:
#include <sstream>
std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
}
Alternatywny sposób C++ od C++11:
#include <stdexcept>
#include <string>
std::string arg = argv[1];
try {
std::size_t pos;
int x = std::stoi(arg, &pos);
if (pos < arg.size()) {
std::cerr << "Trailing characters after number: " << arg << '\n';
}
} catch (std::invalid_argument const &ex) {
std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
std::cerr << "Number out of range: " << arg << '\n';
}
Wszystkie cztery warianty zakładają, że argc >= 2
. / Align = "left" / whitespace; zaznacz isspace(argv[1][0])
jeśli tego nie chcesz. Wszystkie z wyjątkiem atoi
odrzucają końcowe białe znaki.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-10 13:43:34
Zauważ, że Twoje main
argumenty nie są poprawne. Standardowy formularz powinien brzmieć:
int main(int argc, char *argv[])
Lub równoważnie:
int main(int argc, char **argv)
Istnieje wiele sposobów na osiągnięcie konwersji. Jest to jedno podejście:
#include <sstream>
int main(int argc, char *argv[])
{
if (argc >= 2)
{
std::istringstream iss( argv[1] );
int val;
if (iss >> val)
{
// Conversion successful
}
}
return 0;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-09 13:53:57
Można również użyć STD::stoi z string.
#include <string>
using namespace std;
int main (int argc, char** argv)
{
if (argc >= 2)
{
int val = stoi(argv[1]);
// ...
}
return 0;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-22 14:24:02
Jak zauważył WhirlWind, zalecenia dotyczące stosowania atoi
nie są zbyt dobre. atoi
nie ma możliwości wskazania błędu, więc otrzymujesz ten sam zwrot z atoi("0");
, co z atoi("abc");
. Pierwsza jest wyraźnie znacząca, ale druga jest wyraźnym błędem.
Polecił również strtol
, co jest całkowicie w porządku, jeśli jest trochę niezdarny. Inną możliwością byłoby użycie sscanf
, czegoś w rodzaju:
if (1==sscanf(argv[1], "%d", &temp))
// successful conversion
else
// couldn't convert input
Zauważ, że strtol
daje jednak nieco bardziej szczegółowe wyniki -- w szczególności, jeśli masz argument 123abc
, wywołanie sscanf
po prostu powie, że przekonwertowało liczbę (123), podczas gdy strtol
nie tylko przekaże ci, że przekonwertowało liczbę, ale także wskaźnik na a
(tzn. początek części, którą może , a nie zamienić na liczbę).
Ponieważ używasz C++, Możesz również rozważyć użycie boost::lexical_cast
. Jest to prawie tak proste w użyciu jak atoi
, ale zapewnia również (w przybliżeniu) taki sam poziom szczegółowości w raportowaniu błędów jak strtol
. Na największym wydatkiem jest to, że może wyrzucać wyjątki, więc aby go użyć, twój kod musi być bezpieczny dla WYJĄTKÓW. Jeśli piszesz C++, to i tak powinieneś to zrobić, ale to trochę wymusza problem.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-09 14:41:51
Spójrz na strtol (), jeśli używasz standardowej biblioteki C.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-09 13:52:02
Podejście z istringstream można poprawić, aby sprawdzić, czy po oczekiwanym argumencie nie dodano żadnych innych znaków:
#include <sstream>
int main(int argc, char *argv[])
{
if (argc >= 2)
{
std::istringstream iss( argv[1] );
int val;
if ((iss >> val) && iss.eof()) // Check eofbit
{
// Conversion successful
}
}
return 0;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-04 16:38:03
W ten sposób możemy to zrobić....
int main(int argc, char *argv[]) {
int a, b, c;
*// Converting string type to integer type
// using function "atoi( argument)"*
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-08 07:12:46