首页 > 解决方案 > 使用静态转换将字符转换为整数不起作用?

问题描述

我有这个程序,我遇到问题的函数是 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;
}

标签: c++xcodecastingstatic-cast

解决方案


为了使用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());

推荐阅读