c++ - 不知道为什么我不能从字符串转换为整数?
问题描述
string typeVisa (string str);
int main(){
string credit_card;
string type;
getline(cin, credit_card);
type = typeVisa(credit_card);
}
string typeVisa (string str){
int digit1;
int digit2;
digit1 = atoi(str[0]);
digit2 = atoi(str[1]);
// code continues and returns a string
}
“char”类型的参数与“const char *”类型的参数不兼容这是什么意思^^?
解决方案
atoi()
接受一个以空字符结尾的字符串,但您试图将其传递给单个字符。你可以这样做:
char arr[] = {str[0], '\0'};
digit1 = atoi(arr);
arr[0] = str[1];
digit2 = atoi(arr);
...
但是将char
范围内'0'..'9'
的 a 转换为等值整数的更简单方法是'0'
从字符中减去,因此:
'0' - '0' = 48 - 48 = 0
'1' - '0' = 49 - 48 = 1
'2' - '0' = 50 - 48 = 2
And so on...
digit1 = str[0] - '0';
digit2 = str[1] - '0';
推荐阅读
- javascript - 在什么情况下我们会在 javascript 中创建新的内存引用?
- python-3.x - 如何生成一个随机值列表,不包括另一个列表中的值
- javascript - 遍历对象并插入元素
- ios - Cordova 应用程序无法单击元素的确切位置
- java - 在java中实现fread(readInt)
- java - org.hibernate.MappingException Hibernate 映射列
- java - 如何解决Retrofit2接口空指针
- arrays - 列表中的 Dart 对象
- php - 如果包含在列 ID
- node.js - 一次在多个 .js 文件中查找和替换字符串并保存文件