当我运行该程序时,它运行良好,但是由于某种原因,我在输出中出现了随机垃圾。如果我输入的字符串大于11个字符,我将开始出现随机垃圾,如果我输入的字符串小于11个字符,则不会出现随机垃圾,看起来还不错...
#include <iostream>
using namespace std ;
int main ()
{
//Declare and initialize variables
char str1 [100], str2 [100] ;
int i, y ;
//Top display
cout << endl
<< "Copy one string to a second string\n"
<< "----------------------------------\n" ;
//Read user input
cout << "Please enter a string: " ;
cin.getline (str1 , sizeof (str1) ) ;
cout << endl ;
//Make copy using strcpy
for ( i = 0 ; str1[i] != '\0'; i ++ )
{
str2[i] = str1[i] ;
cout << i << " " ;
}
y = sizeof (str2) ;
//Display results
cout << endl
<< "Str1: " << str1 << " has been copied into str2: " << str2 << endl
<< "y: " << y << endl ;
return 0 ;
}
当我运行该程序时,它运行良好,但是由于某种原因,我在输出中出现了随机垃圾。如果输入的字符串大于11个字符,并且输入的字符少于11个,我将开始出现随机垃圾...
它的工作原理。尝试在for
块的末尾和y=sizeof
之间添加以下内容以帮助调试
您只需声明两个字符串就可以用更少的代码来解决这个问题。然后将字符串2设置为字符串1。
您不可以将新字符串终止。循环后这样的事情将达到目的: