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

标签 c++ string loops

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

这是我的代码:

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

Picture of the output

最佳答案

您缺少向字符串 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/

相关文章:

c++ - 防止重新定义构造函数定义的方法

c++ - 有使用 Boost.Log 日志库的经验吗?

c++ - 如何自动将代码添加到 C++ 中的派生函数

r - 为什么循环的执行时间与循环的大小不成正比

C - 多次递归写入一个指针后出现内存访问错误

c++ - 字符串静态成员错误

javascript - 我的餐巾纸数学解析器上复杂正则表达式的逻辑

c - 指向字符串的指针 - C

javascript - 限制为所有字符还是所有数字?

c - 循环时使用文件指针