如何在不使用 printf 语句的情况下获取用户的输入?

问题描述 投票:0回答:0

那是我上面的代码。我必须读入用户输入的 10 个字符串,但我无法弄清楚如何读入这 10 个字符串并将它们存储在一个数组中,而不必打印一条说“输入字符串”的语句。

以上但没有打印声明。该程序的唯一输出应该是按字母顺序排序的 sting

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

#define ARRAY_LENGTH 10
#define MAX_STRING_LENGTH 100

int compare_strings(const void *a, const void *b) {
    return strcmp(*(const char**)b, *(const char**)a);
}

int main() {
    char *strings[ARRAY_LENGTH];
    char input_string[MAX_STRING_LENGTH];
    
    // Read in 10 strings and store them in the array
    for (int i = 0; i < ARRAY_LENGTH; i++) {
        printf("Enter string #%d: ", i+1);
        fgets(input_string, MAX_STRING_LENGTH, stdin);
        input_string[strcspn(input_string, "\n")] = '\0'; // remove newline character
        strings[i] = malloc(strlen(input_string) + 1); // allocate memory for string
        strcpy(strings[i], input_string);
    }

    // Sort the strings in reverse alphabetical order
    qsort(strings, ARRAY_LENGTH, sizeof(char*), compare_strings);

    // Print the sorted strings
    for (int i = 0; i < ARRAY_LENGTH; i++) {
        printf("%s ", strings[i]);
        free(strings[i]); // free memory for string
    }
    printf("\n");

    return 0;
}

c printing printf coding-style scanf
© www.soinside.com 2019 - 2024. All rights reserved.