#include<stdio.h>
#include<stdlib.h>
#define max 100
int main()
{
char str1[max],c;
char str2[max];
int i,n;
printf("请输入一串字符串:");
scanf("%s",str1);
printf("输入插入字符的位置:");
scanf("%d",&n);
fflush(stdin);
printf("要加入的字符:");
scanf("%c",&c);
for(int temp=0;temp<=max;temp++)
{
str2[temp]=str1[temp];
}
str1[n]=c;
str2[n]=c;
printf("%s,%s",str1,str2);
system("pause");
return 0;
}
为什么这里的str1和str2打印出来的结果不一样?
在字符数组的指定位置加入字符的这个程序哪里有问题?求解,谢谢
#include<stdio.h>
#include<stdlib.h>
#define max 100
int main()
{
char str1[max],c;
char str2[max];
int i,n;
printf("请输入一串字符串:");
scanf("%s",str1);
printf("输入插入字符的位置:");
scanf("%d",&n);
fflush(stdin);
if(n<0||n>max+1)
{
printf("输入的位置不合法\n");
}
for(int temp=0;temp<=max;temp++)
{
str2[temp]=str1[temp];
}
printf("%s",str2);
for(int j=i=0;str1[i]!='\0';i++,j++)
{
if(i>n)
{
str2[j+1]=str1[i];
}
}
printf("%s",str2);
system("pause");
return 0;
}
第一个代码,数组长度是100,temp最大是99,在for循环里,temp<max