铸造字符为整数使用静态投不工作? [关闭]

问题描述 投票:0回答:1

我有这个计划,我有一个问题,该功能是stringLength功能。因为它是由我们的教授给我们,我不能改变函数的声明。我有一个问题,这个问题是静态铸造的整数(在这种情况下,我)到一个字符将其插入字符数组。我在网上看着它,显然这样做

A[0]= char(i+48); 

这工作,但我不想用这个,因为我得到这个从互联网。我想用的是

A[0] = static_cast<char>(i);

如果有另一种方式来投它或将不胜感激一个简单的方法。我甚至试着做

 A[0] = i; 
 A[0] = char(i); //or this 

这是我的整个程序。最后一个功能是功能我有一个问题

编辑:我想要达到的输出可以说我用字符串为“卓悦”我想我要说的输出是“7Bonjour”。我的静态浇铸的问题是卓悦之前什么也不显示。该字符串的长度应该在字符串之前出现

编辑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++ xcode casting static-cast
1个回答
1
投票

为了与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());
© www.soinside.com 2019 - 2024. All rights reserved.