C 冒泡排序整数数组 - 输出问题

C Bubble Sort Integer Array - Output Issue

这里是新手。

对于我的 C 编程 class,我需要使用冒泡排序对从输入 .txt 文件中读取的列表进行排序。 .txt 文件中的每一行都有年份、名称和受飓风影响的州 [year] [name] [states]。

例如:

1999 Floyd NC
2003 Isabel NC, VA
2004 Charley FL, SC, NC
2004 Frances FL
...etc.

程序需要按年份对列表进行排序,同时保持所有数据行正确(将相关数组元素放在一起)。我的整数数组冒泡排序工作正常,除了一个问题 - 一行数据不在列表的一侧。这是此问题的示例输出:

    1960    Donna    FL, NC
    1969    Camille  MS     1972    Agnes    FL
    1983    Alicia   TX
    2004    Charley  FL, SC, NC

1972 Agnes FL 行几乎是正确的,但由于某些原因打印到一边而不是在前一行的正下方。

代码:

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

#define MAX_HURCS 30

int main() {
    FILE *hurricaneData;
    int year[MAX_HURCS];
    char name[MAX_HURCS][50];
    char states[MAX_HURCS][50];
    int i = 0, j;
    int count = 0;
    int sort;
    int tempYear;
    char tempName[50];
    char tempStates[50];

    if ((hurricaneData = fopen("hurricanes2.txt", "r")) == NULL) {
        printf("Error: Could not open file");
    }

    while ((fscanf(hurricaneData, "%d %s", &year[i], &name[i]) != EOF)
        && (fgets(states[i], 50, hurricaneData) != NULL)) {
        i++;
        count++;
    }

    for (i = 0; i < count - 1; i++) {
        for (j = 0; j < count - 1 - i; j++) {
            if (year[j] > year[j + 1]) {
                tempYear = year[j];
                year[j] = year[j+1];
                year[j+1] = tempYear;

                strcpy(tempName, name[j]);
                strcpy(name[j], name[j+1]);
                strcpy(name[j+1], tempName);

                strcpy(tempStates, states[j]);
                strcpy(states[j], states[j+1]);
                strcpy(states[j+1], tempStates);
            }
        }
    }
    for (i = 0; i < count; i++) {
        printf(" \t%d\t%s\t%s ", year[i], name[i], states[i]);
    }
    return 0;
}

我也试过这个排序算法,但我遇到了同样的问题:

for (i = 0; i < count; i++) {
    for (j = 0; j < count; j++) {
        if (year[j] > year[i]) {
            tempYear = year[i];
            year[i] = year[j];
            year[j] = tempYear;

            strcpy(tempName, name[i]);
            strcpy(name[i], name[j]);
            strcpy(name[j], tempName);

            strcpy(tempStates, states[i]);
            strcpy(states[i], states[j]);
            strcpy(states[j], tempStates);
        }
    }
}

我认为错误是你文件中的最后一行没有行尾字符,所以它读取到文件末尾,当它打印同一行时它不会移动到下一行所以要么去文本文件中的最后一行并在最后一行放置一个 endl 或为每一行手动打印一个 endl。另一种或更通用的方法是从您的输入中删除新行,可以这样做,在阅读文本时这样做

int len = strlen(states[i]);
if(len>0 && states[i][len-1] == '\n')
{
    states[i][len-1] = '[=10=]';
}

这将删除所有新行,然后您可以在 printf 中手动打印它们