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

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

新手在这里。

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

例如:

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);
        }
    }
}
c arrays sorting integer bubble-sort
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.