我写了一个简单的程序来反转数组。例如,字符串 'hello' 将被打印为 'olleh'。但是,当我输入诸如“hello”之类的内容时,它会打印出一半的字符串,然后是一些不应该出现的神秘字符和其他无意义的内容。
我的源码如下:
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], temp;
int i = 0, j = 0;
printf("Enter a string:\n");
fgets(str, 100, stdin);
// scanf("%s", &str);
j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = str[temp];
i++;
j--;
}
printf("The reversed string is: %s", str);
return (0);
}
我得到的一些输出是“oll”,然后是一个小方 block ,里面有四个数字。这可能会有所不同,有时会在菱形中打印“olx”或“olH”甚至带有问号的“ol”。为什么我的程序不能正常工作?该数组是否已经包含一些其他编码信息?
最佳答案
让我们仔细看看这两行:
temp = str[i];
...
str[j] = str[temp];
首先,您将 temp
设置为 str[i]
中的字符。另一个使用 temp
作为 index 到 str
中。但是 temp
不是一个索引,它是一个字符。所以最后一行应该是
str[j] = temp;
关于c - 为什么我的数组打印不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934074/