c++ - 如何修复 std::stoi 中的 "std::invalid_argument"

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

我正在尝试做一个套接字服务器,但是当我尝试传递数字时,我得到了 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,但我收到了错误。

最佳答案

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

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

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

关于c++ - 如何修复 std::stoi 中的 "std::invalid_argument",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56990627/

相关文章:

c++ - 子弹物理因引用无效而崩溃?

c++ - 在 this 关键字上调用函数

c++ - 与类定义相同类型的静态 constexpr 成员(其他详细信息)

c++ - 找出函数、lambda 或函数的返回类型

c++ - 使用 cctype 库搜索函数以查找范围内数字的字符数

c++ - 为什么这个模板类拥有的类的类型,使用模板类型,无法识别?

c++ - qplaintextedit 行间距

c++ - Phidg​​ets 的包装器不起作用

c++ - 导入 cstring 失败 : include <cstring> error

c - 假设带有 'text/*' 的 HTTP 数据包永远不会有 '\0' 总是安全的吗?