【问题标题】:Sorting strings in C在 C 中对字符串进行排序
【发布时间】:2013-11-21 18:45:22
【问题描述】:

我的任务是编写一个对字符串进行排序的程序(不使用指针,因为我们还没有学过这些)。但我被困住了,我需要一点帮助。这是我目前所拥有的:

#include <stdio.h>

int main()
{
    printf("Enter text to be sorted alphabetically:\n");
    char a[100][100]; // This is my array of text. 
    // It has a maximum of 100 words, each with 100 characters.
    int i = 0;
    while(scanf("%c", a[i][100]) != EOF)
    {
            i++; // This is where I get the string from the user.
            // I think this is where the problem is.
    }
    int l, x, j, m = 0;
    char k[100]; // This is the swap variable for the bubble sort.
    for(l = 0; l < i; l++)
    {
            for(j = 0; l < i - l; j++)
            {
                    if(a[j][m] > a[j+1][m]) 
                    { 
                            for(x = 0; x < 100; x++)
                            {
                                    k[m] = a[j][m]; // Bubble sort.
                                    a[j][m] = a[j+1][m];
                                    a[j+1][m] = k[m];
                            }
                            m = 0; // m is set back to 0.
                    }
                    if(a[j][m] == a[j+1][m])
                    {
                            m++; // m is supposed to represent the mth letter.
                            // so if the first two letters are equal, it increases m.
                            j--;
                    }
            }
    }
    printf("Sorted text is: /n");
    for(l = 0; l < i; l++)
    {
            for(j = 0; j < 100; j++)
            {
                    printf("%s", a[l][j]); // Print out the final result.
                    // I think I messed up this one too.
            }
            printf("\n");
    }
}

此代码拒绝编译。它说:

format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’

谁能告诉我我做错了什么? 谢谢。

【问题讨论】:

  • 实际上,错误中的单词int 可能很重要。你确定你有char a[100][100]吗?会不会是int a[100][100]

标签: c string sorting char alphabetical


【解决方案1】:

对于字符串,scanf 格式说明符为%s

scanf ("%s" ...

你必须提供存储字符串的地址

&a[i][0]

没有人输入超过 99 个字符 :)

【讨论】:

  • 谢谢。那效果很好。代码仍然无法正常工作,但我解决了我的错误。我可以从这里拿走。
  • @user2973526:欢迎来到 Stackoverflow!请尽快阅读About 页面。现在,请阅读Help! Someone answered my question!
猜你喜欢
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
  • 2016-02-05
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
相关资源
最近更新 更多