gpt4 book ai didi

c++ - 使用静态转换将字符转换为整数不起作用?

转载 作者:行者123 更新时间:2023-11-28 04:25:01 24 4
gpt4 key购买 nike

<分区>

我有这个程序,我遇到问题的函数是 stringLength 函数。我无法更改我们的教授给我们的函数声明。我遇到的问题是将整数(在本例中为 i)静态转换为字符以将其插入字符数组。我在网上查了一下,显然是这样做的

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

这行得通,但我不想使用它,因为我是从 Internet 上下载的。我要用的是

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;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com