C:字符串数组 - 输入大小为n时,只能输入n-1个字符串

时间:2013-05-08 15:29:35

标签: c arrays string multidimensional-array bubble-sort

我必须使用冒号排序技术按字典顺序对字符串进行排序,而不使用任何库函数。我编写了以下代码,它在排序字符串时工作正常。

但问题是,如果我将 n 作为输入(比如n = 4),我只能输入 n-1 字符串(只有3个字符串)。 通过将for循环从0运行到n可以解决该问题,但这不是一个合理的解决方案。

我在这里做错了什么?

#include <stdio.h>
#include <string.h>
#include <malloc.h>
void swap(int indx[], int j)
{
    int temp;
    temp = indx[j];
    indx[j] = indx[j+1];
    indx[j+1] = temp;
}
void sort(char **str, int indx[], int n)
{
    int i, j, k;
    for(i=0; i<n; i++)
    {
        for(j=0; j<n-i-1; j++)
        {
            k = 0;
            while(str[j][k] != '\0')
            {
                if((str[indx[j]][k]) > (str[indx[j+1]][k]))
                {
                    swap(indx, j);
                    break;
                }
                else if((str[indx[j]][k]) < (str[indx[j+1]][k]))
                    break;
                else
                    k++;
            }
        }
    }
}
void display(char **str, int indx[], int n)
{
    int i;
    printf("Sorted strings : ");
    for(i=0; i<n; i++)
        printf("%s\n", str[indx[i]]);
}
int main(void)
{
    char **str;
    int n, i, j, *indx;
    printf("Enter no. of strings : ");
    scanf("%d", &n);
    str = (char **) malloc (n * (sizeof(char *)));
    indx = (int *) malloc (n * sizeof(int));
    for(i=0; i<n; i++)
        str[i] = (char *)malloc(10 * sizeof(char));
    printf("Enter the strings : ");
    for(i=0; i<n; i++)
    {
        gets(str[i]);
        indx[i] = i;
    }
    sort(str, indx, n);
    display(str, indx, n);
}

3 个答案:

答案 0 :(得分:3)

问题在于您使用scanf()。执行scanf("%d", &n)时,scanf()函数读取输入,直到找到整数,并将值放入n。但是,当您输入该整数时,您不只是键入'4',键入'4'并按Enter键。并且换行符仍在输入缓冲区中。另一方面,gets()函数读取的输入并包括第一个换行符,并且丢弃换行符。因此,当您读取输入字符串时,对gets()的调用会读取换行符,并立即返回。然后,您输入的第一个字符串将在第二次调用gets() ...

时读取

顺便说一下,gets()函数在任何情况下都不应该永远用于实际程序,因为它不允许你限制输入。更好的是使用fgets()fgets(str[i], BUFFERSIZE-1, stdin)

答案 1 :(得分:0)

int main(void)
{
char **str;
int n=4, i, j, *indx;
printf("Enter no. of strings : ");
//scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
    str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
    gets(str[i]);
    indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}

//如果我注释掉scanf并给它赋值,它可以正常工作//               所以问题是在scanf之后使用fgets,因为scanf在缓冲区中留下一个换行符//所以在使用fgets之前消耗它

答案 2 :(得分:0)

在您必须输入字符串的行处尝试此操作。而不是:

gets(str[i]);

型:

scanf("%s",str[i]);
相关问题