C++ 代码输出随机符号,i';我不知道怎么了
我制作了一个程序,将全名缩短为首字母,并删除输入内容之间的空格。它以前可以工作,但现在它打印首字母,但也打印随机符号?我真的不明白它为什么这么做。我也是编程新手 这是我的代码:C++ 代码输出随机符号,i';我不知道怎么了,c++,string,loops,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]
// 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;
}
//此代码从输入的名称中删除空格
char*removespace(char*str)
{
int i=0,j=0;
while(str[i])
{
如果(str[i]!='')
str[j++]=str[i];
i++;
}
str[j]='\0';
返回str;
}
//此代码采用用户名,并将其缩短(sh)
内部主(空){
char-str[100],sh[20];
int j=0;
cout将字符串终止符('\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;
}
#包括
char*removespace(char*str)
{
int i=0,j=0;
while(str[i])
{
如果(str[i]!='')
str[j++]=str[i];
i++;
}
str[j]='\0';
返回str;
}
//此代码采用用户名,并将其缩短(sh)
内部主(空){
char-str[100],sh[100];
int j=0;
cout您在main
函数中的for
循环后漏掉了一行(我猜),这意味着您的字符串可能不是以null结尾的
使用removeSpaces
函数中相同的(正确的)逻辑,只需在main
中的for
循环之后添加这一行:
sh[++j] = '\0\;
sh[++j]='\0';
完成后,您不会使用\0
终止sh
,但是removeSpaces()
希望字符串末尾有一个空字符。因此,removeSpaces()
可能会超出预期的边界
只需在main()
中的for
之后添加这一行:
警告:在设置之前,您应该始终确保j
的大小小于20(小于sh
)。否则,您可能会越过sh
的边界。这也可能成为问题的根源。“它以前确实有效,但是”你更改了什么?那是什么时候?我想我没有更改任何东西,我确实保存了它并离开了。但我一定是不小心更改了什么东西?这是几天前我最后一次触摸它。你的代码看起来不错。唯一困扰我的是,如果你发送了类似“一些文本”的内容<代码> >代码> STR ,因为C++中字符串字是常数,所以您将调用未定义的行为。请您将整个程序张贴而不是只发布一个函数。突然不再工作是未定义行为的标志,例如当您忽略空终止字符串时…