首页 > 解决方案 > 代码输出随机符号,我不确定出了什么问题

问题描述

我制作了一个程序,可以将全名缩短为首字母,并删除输入内容之间的任何空格。它以前确实有效,但现在它打印首字母但也打印随机符号?我真的不明白它为什么这样做。我也是编程新手。

这是我的代码:

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

输出图片

标签: c++stringloops

解决方案


您缺少将字符串终止符 ('\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


推荐阅读