首页 > 解决方案 > 如何修复 std::stoi 中的“std::invalid_argument”

问题描述

我正在尝试做一个套接字服务器,但是当我尝试传递我得到的数字时std::invalid_argument,我不知道为什么。我重新编写了代码以使其更简单,这里是:

std::string a = std::to_string(32);
char texto[5];
strcat(texto,a.c_str());
printf("%s", texto);//Isn't printing a string that you can convert to a number
std::string b = texto;
int s = std::stoi(texto);
std::cout << s;

我希望输出为 32,但我得到了错误。

标签: c++c++11c-strings

解决方案


char texto[5];
strcat(texto,a.c_str());

texto未初始化,因此它包含垃圾值。strcat必须首先阅读它们以寻找 NUL 终止符,从而为您提供未定义的行为。

您可能正在寻找strcpy而不是strcat.


推荐阅读