我有一串数字,例如“123456789”,我需要提取每个数字以在计算中使用它们。我当然可以通过索引访问每个 char,但是如何将它转换为 int?
我研究了 atoi(),但它需要一个字符串作为参数。因此,我必须将每个字符转换为字符串,然后在其上调用 atoi。有没有更好的办法?
您可以利用数字的字符编码都是从 48(对于“0”)到 57(对于“9”)的顺序这一事实。这适用于 ASCII、UTF-x 和几乎所有其他编码(有关此内容的更多信息,请参见下面的评论)。
因此,任何数字的整数值都是数字减去“0”(或 48)。
char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'
是同义词
char c = '1';
int i = c - 48; // i is now equal to 1, not '1'
但是我发现第一个c - '0'
更具可读性。
#define toDigit(c) (c-'0')
或者您可以使用“正确”方法,类似于您原来的 atoi 方法,但使用 std::stringstream 代替。这应该使用字符作为输入以及字符串。(boost::lexical_cast 是更方便语法的另一个选项)
(atoi 是一个旧的 C 函数,通常建议尽可能使用更灵活和类型安全的 C++ 等效项。std::stringstream 涵盖与字符串的转换)
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
int num ;
num = atoi(argv[1]);
printf("\n%d", num);
}
#include<iostream>
#include<stdlib>
using namespace std;
void main()
{
char ch;
int x;
cin >> ch;
x = char (ar[1]);
cout << x;
}
如果您担心编码,您可以随时使用 switch 语句。
请注意保存这些大数字的格式。在某些系统中,整数的最大大小低至 65,535(32,767 有符号)。其他系统,你有 2,147,483,647(或 4,294,967,295 未签名)
以下方法有什么问题吗?
int CharToInt(const char c)
{
switch (c)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
return 0;
}
}
通过这种方式,您可以轻松地将 char 转换为 int 并将 int 转换为 char:
int charToInt(char c)
{
int arr[]={0,1,2,3,4,5,6,7,8,9};
return arr[c-'0'];
}
我同意@jalf。使用sstream库和stoi似乎是推荐的方法:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
stringstream st;
st << 1 << '2';
cout << stoi(st.str()) + 1;
return 0;
}
13
我是 C++ 的新学生,但长期从事 LAMP 堆栈开发。我希望字符串类有更多的东西可以在字符和字符串之间平滑过渡,但我还没有找到原生支持的东西。
对我来说,以下工作非常好:
QChar c = '5';
int x = c.digitValue();
// x is now 5
文档:int QChar::digitValue() const它说:
返回数字的数值,如果字符不是数字,则返回 -1。