c++ - 代码输出随机符号,我不确定出了什么问题
问题描述
我制作了一个程序,可以将全名缩短为首字母,并删除输入内容之间的任何空格。它以前确实有效,但现在它打印首字母但也打印随机符号?我真的不明白它为什么这样做。我也是编程新手。
这是我的代码:
// 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;
}
解决方案
您缺少将字符串终止符 ('\0') 添加到字符串 sh。下面是程序。
#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
推荐阅读
- python - 如何防止 pyinstaller 报错?
- javascript - 仅在附加时才关注输入
- python - Python 2.7 pip install 失败缺少 pyconfig.h,可能安装的源分发错误?
- mysql - mysql symfony中左连接时如何确定排序字段?
- javascript - 从字典列表中提取值并填充组件
- docker - docker 中的 java 应用程序如何在 ubuntu 18.4 的挂载点中定位文件
- c++ - C++,程序认为我没有 main 函数,当我这样做并给出“_main”时,引用自:implicit entry/start for main executable error
- ios - Xcode 12.0 中是否有任何更改将 ButtonType 从 roundedRect 更改为 system?
- ruby-on-rails - Rails slim 将 html 渲染为文本
- jquery - 如何在 jQuery 中使用嵌套的 foreach 循环?