【发布时间】:2014-11-19 06:58:56
【问题描述】:
我正在尝试创建 C 程序来读取文本文件并按升序对其进行排序。文本文件的例子是
2
3; 2, 5, 7
6; 4, 7, 8, 9, 5, 2
用第一行表示行数,“;”后面的数字表示元素每行和元素之间用“,”分隔。 所以我的想法是创建一个以行作为第一个数字的动态锯齿状数组,然后将每一行指向带有元素的不同数组。首先对指针数组进行排序,然后对每个数组的元素进行排序。这是我迄今为止尝试过的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int SortLists();
int main ()
{
int i,j = 0;
char filename[10]; //name of the file
char line[100];
int rows = 3; //I have to initialized this to test my code first
int cols;
int **jaggedArr; //jagged array
jaggerArr = malloc (rows*sizeof(int*)) ;
printf("Enter the file name with .txt : ");
scanf("%s", filename);
FILE *filePtr = fopen(filename, "r");
int num;
if (filePtr != NULL)
{
while (fgets(line, sizeof(line), filePtr) != NULL) //read each line of the text
{
cols = atoi(strtok(line, ";")); //use strtk to break elements
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
jaggedArr[i][j] = atoi(strtok(line, ",")); //parse into the jagged array
}
}
}
fclose(filePtr);
}
}
int SortLists(int list[], int size) //sort method
{
int i,j,temp;
for (i = 0; i < size; ++i)
{
for (j = i + 1; j < size; ++j)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
作为 C 的初学者,我对指针的概念并不熟悉,这与 C# 有很大不同。 对不起我的英语不好,因为它不是我的第一语言。非常感谢你帮助我。
【问题讨论】:
-
重复的
strtok(line, ",")不会做你想做的事。由';'分隔的开瓶器看起来很有希望,但行处理的其余部分应使用strtok(NULL, ',')完成。也许为这些行分配一些内存? -
感谢您花时间回答我的问题。通过分配内存,你的意思是使用行中的元素数来初始化数组的大小吗?
标签: c sorting jagged-arrays