我目前正在从文件中读取单词列表,并尝试逐行对它们进行排序。我可以读入每一行,并将单词打印出来,但似乎不能单独对每一行进行排序。第一行已排序,但第二行未排序。有人能看出我哪里错了吗?谢谢!
int fd;
int n_char = 0;
int charCount = 0, wordCount = 0, lineCount = 0;
int wordsPerLine[100];
char buffer;
char words[6][9];
fd = open(inputfile, O_RDONLY);
if (fd == -1) {
exit(1);
}
wordsPerLine[0] = 0;
/* use the read system call to obtain 10 characters from fd */
while( (n_char = read(fd, &buffer, sizeof(char))) != 0) {
if (buffer == '\n' || buffer == ' ') {
words[wordCount][charCount] = '\0';
charCount = 0;
wordCount++;
wordsPerLine[lineCount] += 1;
if (buffer == '\n') {
lineCount++;
wordsPerLine[lineCount] = 0;
}
} else {
words[wordCount][charCount++] = buffer;
}
}
printf("Num Words: %d --- Num Lines: %d\n", wordCount, lineCount);
char tmp[9];
int m, n;
int i, x, totalCount = 0;
for (i = 0; i < lineCount; i++) {
for (x = 0; x < wordsPerLine[i]; x++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = 0; n < wordsPerLine[i]; n++) {
if(strcmp(words[n-1], words[n])>0) {
strcpy(tmp, words[n-1]);
strcpy(words[n-1], words[n]);
strcpy(words[n], tmp);
}
}
} /* end sorting */
}
}
printf("Sorted:\n");
totalCount = 0;
for(i = 0; i < lineCount; i++) {
printf("Line %d (%d words)\n", i + 1, wordsPerLine[i]);
for(x = 0; x < wordsPerLine[i]; x++) {
printf("%s\n", words[totalCount++]);
}
}我的示例输入文件是:
great day out
foo bar food发布于 2014-06-20 07:20:04
让我们分成小部分..。
要查看问题是否在阅读中,请注释阅读部分,并尝试添加以下内容:
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};并将计数器设置为与此输入相同的值。
你的循环正在访问一些越界的数据...我建议你先用一个数字数组来尝试你的排序代码,看看它是否正确地排序了它们……
#include<stdio.h>
#define N 6
int main()
{
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};
int numbers[] = {20, 10, 50, 5, 30, -50};
int i, j, temp;
for(i = 0; i < N - 1; i++)
for(j = 0; j < N - 1; j++)
if(numbers[j] > numbers[j + 1])
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
for(i = 0; i < N; i++)
{
printf("%d\n", numbers[i]);
//printf("%s\n", words[i]);
}
}另请注意,这是冒泡排序效率最低的实现(但与您提供的相同),您可以通过添加一个变量来改进它,以检查内部循环中发生的某些更改(这意味着它已经排序,您可以停止排序)……
此外,在外部循环的每次迭代之后,将把一个元素放在其最后的位置(尝试找出是哪一个),这意味着您将不需要在下一次迭代中考虑该元素,因此在外部循环中的每次迭代之后,内部循环中比较的元素的数量可以减少1……
你可以找到更多关于冒泡排序here的信息
发布于 2014-06-20 08:37:10
/* iterate through each line */
for (i = 0; i < lineCount; i++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = m+1; n < wordsPerLine[i]; n++) {
if(strcmp(words[n + totalCount], words[m + totalCount]) < 0) {
strcpy(tmp, words[m + totalCount]);
strcpy(words[m + totalCount], words[n + totalCount]);
strcpy(words[n + totalCount], tmp);
}
}
} /* end sorting */
totalCount += wordsPerLine[i];
}我只需要对每一行中的每个单词进行统计,这样我就知道应该从哪一行开始比较
https://stackoverflow.com/questions/24310663
复制相似问题