2016-10-02 56 views
0

我想创建一个C程序,它接受控制台中的一行字符,将它们存储在数组中,颠倒数组中的顺序,并显示反转的字符串。我不允许使用getchar()printf()以外的任何库函数。我的尝试如下。当我运行程序并输入一些文本并按下Enter时,什么都不会发生。有人能指出错误吗?C程序获取字符到数组和相反顺序

#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

您正在尝试这样解决的三个问题一次:将一个字符串读入一个数组,反转并显示它。一次解决它们,并且不要试图将它们结合起来,直到它们完美地工作。 – Beta

+0

您是否建议像使每个问题成为一个单独的功能并分别测试每个问题?我们还没有很多,但我相信这是一个更好的方法。 – yroc

+0

你可以这样做,或者你可以写三个独立的*程序*,并单独测试它们。相信我,它可以为你节省很多麻烦。 – Beta

回答

2

好像在这个while循环:

while (my_strg[i] != '\0') 
{ 
    end_of_string++; 
} 

你应该增加i,否则如果my_strg[0]不等于'\0',这是一个无限循环。 我建议放一个断点,看看你的代码在做什么。

+0

你钉了它!在发布之前,我实际上正在玩着_gdb_,但是很难过。按照我们教授的要求,我没有在IDE中工作。我们的教授说,我们将在后面的课程中介绍调试(!),但似乎是一个足够重要的话题,可以在开头介绍 - 至少是它的基础知识。 – yroc

+0

实际上有简单的调试方法,没有适当的调试。例如,你可以使用'printf(“before while loop \ n”);'和'printf(“while while循环”);'以获知程序停滞在哪里。 – peval27

+0

好的,这是一个很好的技巧。谢谢。 – yroc

1

我想你应该看看你的第二个while循环,并问自己哪里my_string [i]的递增,因为对我来说,它看起来像它始终在零...

+0

是的,你是正确的@佩瓦尔27也指出。谢谢。 – yroc