繁体   English   中英

代码输出随机符号,我不确定出了什么问题

[英]Code outputs random symbols, i'm unsure what is wrong

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

这是我的代码:

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

output图片

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

您在main function 中的for循环之后错过了一行(我猜),这意味着您的字符串可能不是以空值结尾的。

使用您在removeSpaces function 中的相同(正确)逻辑,只需在main中的for循环之后立即添加此行:

sh[++j] = '\0';

完成后,您不会用\0终止sh ,但removeSpaces()期望字符串末尾有一个 null 字符。 因此, removeSpaces()可以 go 超出您的预期边界。

只需在你的for in main()之后添加这一行:

sh[++j] = '\0\;

警告词:在设置之前,您应该始终确保j < 20( sh的大小)。 否则,您可以 go 越过sh的边界。 这也可能成为问题的根源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM