我正在读取文件中的单词列表并尝试逐行排序。 我可以阅读每一行并打印好的单词,但我似乎无法单独排序每一行。第一行是排序的,但第二行不是。谁能看到我哪里出错了?谢谢!
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
答案 0 :(得分:0)
让我们去一小部分......
要查看问题是否在阅读中,请评论阅读部分并尝试添加:
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]);
}
}
另请注意,这是冒泡排序效率最低的(但与您提供的相同),您可以通过添加变量来检查内部循环中的某些更改(例如,这意味着它是已经排序,你可以停止排序)...
此外,在outter循环上的每次迭代之后,一个元素将被放置在其最终位置(尝试找出哪一个),这意味着您不需要在下一次迭代中考虑此元素,所以在外循环中的每次迭代之后,内循环中比较的元素数量可以减少1 ...
您可以找到有关冒泡排序here
的更多信息答案 1 :(得分:0)
/* 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];
}
我只需要保持每行每个单词的运行计数,所以我知道要开始与
比较的行