【发布时间】:2021-12-13 13:01:33
【问题描述】:
我正在使用这个 atoi 从字符串中删除所有字母。但是我的字符串使用了如下所示的特殊字符,因此我的 atoi 退出时出现错误。我该怎么做才能解决这个问题?
#include <iostream>
#include <string>
using namespace std;
int main() {
std::string playerPickS = "Klöver 12"; // string with special characters
size_t i = 0;
for (; i < playerPickS.length(); i++) { if (isdigit(playerPickS[i])) break; }
playerPickS = playerPickS.substr(i, playerPickS.length() - i); // convert the remaining text to an integer
cout << atoi(playerPickS.c_str());
}
这是我认为的错误。我只有在使用那些特殊字符时才会得到这个,这就是为什么我认为这是我的问题。
【问题讨论】:
-
当你说你的“atoi exits with an error”是什么意思?什么“错误”?请edit您的问题向我们提供更多详细信息。也请花一些时间阅读the help pages,阅读SO tour,阅读How to Ask,以及this question checklist。
-
有什么办法可以去除字符串中的特殊字符?
-
@AlexanderStröm 这是一个完全独立的问题。您的代码 sn-p 不完整。这是一个微不足道的案例,您应该能够轻松地生成 minimal reproducible example。
-
您的编译器使用什么编码来创建字符串文字,或者字符串中每个字节的值是什么?你打电话给
setlocale了吗? -
Why shouldn't I use atoi()? (duplicate)。请改用
strtol