我试图创建一个C程序,它接受来自控制台的一行字符,将它们存储在一个数组中,反转数组中的顺序,并显示反转的字符串。我不允许使用getchar()
和printf()
以外的任何库函数。我的尝试如下。当我运行程序并输入一些文本并按Enter键时,没有任何反应。有人可以指出错误吗?
#include <stdio.h>
#define MAX_SIZE 100
main()
{
char c; // the current character
char my_strg[MAX_SIZE]; // character array
int i; // the current index of the character array
// Initialize my_strg to null zeros
for (i = 0; i < MAX_SIZE; i++)
{
my_strg[i] = '\0';
}
/* Place the characters of the input line into the array */
i = 0;
printf("\nEnter some text followed by Enter: ");
while ( ((c = getchar()) != '\n') && (i < MAX_SIZE) )
{
my_strg[i] = c;
i++;
}
/* Detect the end of the string */
int end_of_string = 0;
i = 0;
while (my_strg[i] != '\0')
{
end_of_string++;
}
/* Reverse the string */
int temp;
int start = 0;
int end = (end_of_string - 1);
while (start < end)
{
temp = my_strg[start];
my_strg[start] = my_strg[end];
my_strg[end] = temp;
start++;
end--;
}
printf("%s\n", my_strg);
}
答案 0 :(得分:2)
似乎在这个while循环中:
while (my_strg[i] != '\0')
{
end_of_string++;
}
你应该增加i
,否则如果my_strg[0]
不等于'\0'
,那就是无限循环。
我建议设置断点并查看代码正在做什么。
答案 1 :(得分:1)
我认为你应该看看你的第二个while循环,并问自己my_string [i]在哪里递增,因为对我来说它看起来总是在零......