我被要求编写一个程序,使用getchar()函数填充两个8字母数组。然后我被要求交换两个阵列。
int main(void)
{
char arr1[8];
char arr2[8];
char c;
int counter = 0;
char hold[8];
printf("Please enter 8 characters (Array 1):\t");
while(counter < 8)
{
c = getchar();
arr1[counter] = c;
counter++;
}
counter=0;
printf("Please enter 8 characters (Array 2):\t");
while(counter < 8)
{
c = getchar();
arr2[counter] = c;
counter++;
}
counter=1;
while (counter !=9)
{
printf("\n%c",arr1[counter-1]);
printf("\t%c",arr2[counter]);
counter++;
}
counter=0;
while (counter!=8)
{
hold[counter] = arr1[counter];
arr1[counter] = arr2[counter];
arr2[counter] = hold[counter];
counter++;
}
printf("\n\n\n");
counter=1;
while (counter !=9)
{
printf("\n%c",arr1[counter-1]);
printf("\t%c",arr2[counter]);
counter++;
}
return 0;
}
任何人都可以告诉我在交换数组时我做错了什么?
编辑:我已经意识到它可能是我的第二个printf搞砸了,实际上并没有交换阵列。
答案 0 :(得分:1)
交换代码没有问题,打印数组的方式有一些问题:
while (counter !=9)
{
printf("\n%c",arr1[counter-1]); // why -1?
printf("\t%c",arr2[counter]); // will access array out of bounds (index 8)
counter++;
}
这是纠正的方式:
for(counter=0;counter<8;counter++)
{
printf("\n%c",arr1[counter]);
printf("\t%c",arr2[counter]);
}
此外,您可以通过不使用hold
的数组来简化交换代码:
char hold;
...
for(counter=0;counter<8;counter++)
{
hold = arr1[counter];
arr1[counter] = arr2[counter];
arr2[counter] = hold;
}
正如aruisdante建议的那样,for
循环比while
循环更适合您的用例
答案 1 :(得分:0)
每个数组只占用4个字符,因为您在读取字符后没有刷新标准输入。你的交换逻辑也是错误的。您可以使用以下内容。而是纠正交换逻辑。
int main(void)
{
char arr1[8 + 1] = {'\0'};
char arr2[8 + 1] = {'\0'};
char c;
int counter = 0;
printf("Please enter 8 characters (Array 1):\t");
while(counter < 8)
{
c = getchar();
arr1[counter++] = c;
__fpurge(stdin);
}
arr1[counter] = '\0';
counter=0;
printf("Please enter 8 characters (Array 2):\t");
while(counter < 8)
{
c = getchar();
arr2[counter++] = c;
__fpurge(stdin);
}
arr2[counter] = '\0';
puts(arr1);
puts(arr2);
int i;
for (i = 0; i < 8; i++) // This will do the swapping.
{
c = arr1[i];
arr1[i] = arr2[i];
arr2[i] = c;
}
puts(arr1);
puts(arr2);
return 0;
}
__fpurge(stdin);
用于在每次获取角色时刷新stdin缓冲区。否则getchar()也会将换行符(Enter键)作为一个字符,因此在这种情况下,您只能读取4个字符。并且您可能会考虑使用空字符终止char数组,为此目的,数组大小应始终为您所需的大小+ 1。