如何使用 scanf() 按字母顺序对字符串中的字符进行排序并将字符保存在缓冲区中?

How to sort characters in a string alphabetically using scanf() and saved character in buffer?

嗨,我对使用 C 还很陌生。 我的老师告诉我编写一个函数,通过使用数组按字母顺序对字符串中的字符进行排序,并且当 scanf() 一个字符串时,第一个字符被调用,其余字符保存在缓冲区中。 (我还没有学过指针。)

例如,如果我输入 badf 和 space(信号 "an end",或字符串结尾的标记值),函数应该 return abdf.

我被困在这里了。这是我的第一个 Whosebug 问题!请帮忙。谢谢

#include <stdio.h>
#include <string.h>

int main() {
    char arr[100];
    char front_char, first_char;
    // set the variables
    int i, j, k, l;

    printf("Enter a string and press space to end\n");

    // get the input using scanf, which will just get the first character and save the rest in buffer
    scanf("%c", &first_char);
    // assign the first_character in arr[0] for initialization
    arr[0] = first_char;

    // 32 is "space" in ascii code. Space is used as a sentinel value. User is supposed to press space at the end of the String
    while(front_char != 32) {
        // get the "second" character from buffer and ass. repeat this until the next character in buffer is 32, or "space"
        scanf("%c" , &front_char);

        // load character from buffer, and check if its assigned number in ascii code is smaller than characters in array
        for(i = 1; front_char != 32; i++) {
            for(j = 0; j < i; j++) {
                // go through the previously aligned array to compare the ascii number of the loaded character from buffer
                if(arr[j] <= front_char) {
                    continue;
                } else {
                    // run through the previously aligned array, and if a character with bigger ascii number comes up,
                    for(k = i-1; k >= j; k--) {
                        // assign/push the values in array to the next index(i don't know how to describe this, but I hope you see what I mean..)
                        arr[k+1] = arr[k];
                    }
                }
                // assign the loaded character according its ascii number size
                arr[j] = front_char;
            }
        }

        // print the result
        for(l = 0 ; l < i ; l++){
            printf("%c", arr[l]);
        }
    }

    return 0;
}

例如,如果我输入 badf 和 space(信号 "an end",或字符串结尾的标记值)

您想将输入作为字符串 ex-badf 但您正在将输入作为字符变量。

scanf("%c" , &first_char); 

第二个-

while(front_char != 32)  

正在检查 front_char 是否为 space 但 front_char 中没有存储任何值。

只要你输入,程序就会崩溃!!

要获得最终解决方案,您必须完成三个中间步骤:

  1. 读入字符串成功
  2. 处理字符串中的单个字符
  3. 转置字符串中的字符

你肯定有错误(ameyCU 的回答)。

先尝试读入字符串,再打印出来;没有其他动作。

完成后,尝试读入字符串,然后逐个字符地打印出来。

如果你能做到这一点,那么你已经准备好进行第 3 步并且即将完成。

编辑:另外,当你到达那里时,

while(front_char != ' ')

优于!= 32;它更可靠,更容易阅读和理解。