gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:58 25 4
gpt4 key购买 nike

<分区>

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

例如,如果我输入 badf 和空格(表示“结束”或字符串结尾的标记值),该函数应返回 abdf。

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

#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;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com