我制作了一个程序,可以将全名缩短为首字母缩写,并删除输入内容之间的任何空格。它以前确实有效,但现在它不仅打印首字母缩写,而且还打印随机符号?我真的不明白它为什么这样做。我也是编程新手。
这是我的代码:
// This code removes the spaces from the inputted name
char *removeSpaces(char *str)
{
int i = 0, j = 0;
while (str[i])
{
if (str[i] != ' ')
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
// This code takes the users name, and shortens (sh) it
int main(void) {
char str[100],sh[20];
int j=0;
cout<<"Enter Full Name :";
cin.getline(str,30);
for(int i=0;i<strlen(str);i++)
{
if(i==0){
sh[j]=str[i];
sh[++j]=' ';
}
else if(str[i]==' '){
sh[++j]=str[i+1];
sh[++j]=' ';
}
}
// This then takes the remove spaces code, and prints the initials with a new line
cout << removeSpaces(sh) <<endl;
cout << "\n" <<endl;
return 0;
}
最佳答案
您缺少向字符串 sh 添加字符串终止符 ('\0')。下面是程序。
#include <stdio.h>
char *removeSpaces(char *str)
{
int i = 0, j = 0;
while (str[i])
{
if (str[i] != ' ')
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
// This code takes the users name, and shortens (sh) it
int main(void) {
char str[100],sh[100];
int j=0;
cout<<"Enter Full Name :";
cin.getline(str,30);
for(int i=0;i<strlen(str);i++)
{
if(i==0){
sh[j]=str[i];
sh[++j]=' ';
}
else if(str[i]==' '){
sh[++j]=str[i+1];
sh[++j]=' ';
}
}
sh[j+1] = '\0';
// This then takes the remove spaces code, and prints the initials with a new line
cout << removeSpaces(sh) <<endl;
cout << "\n" <<endl;
return 0;
}
输入全名:ra me ge rmg
关于c++ - 代码输出随机符号,我不确定出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58674664/