c++ - 使用静态转换将字符转换为整数不起作用?
问题描述
我有这个程序,我遇到问题的函数是 stringLength 函数。我无法更改教授给我们的函数声明。我遇到的问题是将整数(在本例中为 i)静态转换为字符以将其插入字符数组。我在网上查了一下,显然是这样做的
A[0]= char(i+48);
这可行,但我不想使用它,因为我是从互联网上得到的。我想要使用的是
A[0] = static_cast<char>(i);
如果有另一种投射方式或一种简单的方式,将不胜感激。我什至试着做
A[0] = i;
A[0] = char(i); //or this
这是我的整个程序。最后一个功能是我遇到问题的功能
编辑:我想要实现的输出可以说我使用的字符串是“Bonjour”,我想要它说的输出是“7Bonjour”。我的静态演员表的问题是在 Bonjour 之前什么都没有出现。字符串的长度应该出现在字符串之前
编辑 2:我简化了代码,只包含与我的问题有关的重要功能和内容
#include <iostream>
#include <fstream>
using namespace std;
ifstream in ("input.txt");
ofstream out ("output.txt");
void stringCopy(char *A, char *B);
bool stringCompare(char *A, char *B);
void stringConcatenation (char *A, char *B);
int stringPosition(char *A, char B);
int stringLength(char *A);
int main (){
char str1[15], str2[15];
char pos;
int number;
if(!in){
cout << "File not opening" << endl;
}
else{
cout << "File opened" << endl;
}
in >> str1;
stringLength(str1);
out << " Contents of the array after string Length: " << str1 << endl;
in.close();
out.close();
}
void stringConcatenation (char *A, char *B){
int i;
int j;
for (i = 0; A[i]!='\0';i++){ // find the last position of the first string
}
for (j = 0; B[j]!='\0';j++){
A[i++] = B[j]; // add the first letter of the second string to the next spot of the first string
A[i]='\0';
}
}
int stringLength(char *A){
char arr[15];
int i = 0;
while (A[i]!='\0'){
arr[i]=A[i];
i++; // increment i one more to store NULL position in temp array
}
arr[i]='\0'; //set last position of the temp array to NULL
A[0]= static_cast<char>(i); //static cast i to char and add to first position
A[1]= '\0'; // sets the last position of the first array for the string concatenation to work and detect end of array
stringConcatenation(A, arr);
return i;
}
解决方案
为了使用static_cast
,您必须这样做:
A[0] = static_cast<char>(i + 48);
静态转换实际上所做的是将 int 转换为具有相应 ASCII 值的 char 。因为 '0' 的 ASCII 值是 48,对于i <= 9
,它会给出正确的输出。
但是如果i >= 10
.
相反,您必须这样做:
strcpy(A, to_string(i).c_str());
推荐阅读
- mysql - mysql - 所有用户每小时的汇总结果
- string - 新样式格式说明符引发标记化错误
- curl - PHP & RabbitMQ & 执行远程控制器,通过 curl 从其他 Web 服务器下载数据
- django - Django REST Framework 在 Gunicorn 上运行缓慢
- java - Realm 用户身份验证:如何在注册 Realm 的 SyncCredentials API 时传递其他用户信息?
- react-native - 如果使用 react-native-vector-icons,则为 react-navigation 抽屉活动图标着色
- php - 读取用户输入并检查数据类型
- multithreading - 控制台应用程序 - DbContext 实例不能在 OnConfiguring 内部使用
- angular - 如何将 img 绑定值传递给另一个组件 - Angular 2+
- css - 如何通过 CSS 设置输入字段的最大整数值?