我正在编写一个程序,该程序将要求用户提供'n'值,然后他们将输入将存储在数组中并分类的'n'值。我已经做了很容易的事情。我将将此数组与文本文件中读取的数字的输入进行比较。如果数字大于任何当前数组值中的任何一个,它将替换它们并将其余的向下滑动。这创建了最大的" n"值的数组
示例: n = 4 n值是:999 972 954 462 937
a[4] = {999, 972, 954, 462, 937};
排序:
a[4] = {999, 972, 954, 937, 462};
如果文件输入为968,则结果是。诉讼:
a[4] = {999, 972, 968, 937, 937};
这是我当前的代码。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if (argc<3) //error checking
return -1;
int size = atoi(argv[2]);
int a[size];
int i, j, temp=0;
printf("Enter %d numbersn", size); //user array input for size and n values
for(i = 0; i < size; i++)
scanf("%d", &a[i]);
for(i=0; i < size; i++){ //sorting array
for(j = i+1; j <size; j++){
if( a[i] < a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
FILE *input;
input = fopen(argv[1], "r");
if(input ==NULL) //error checking
return -1;
if(fscanf(input, "%d", &temp) != 1)
return -1;
while(fscanf(input, "%d", &temp) ==1){ //loop while there is file input
for(i =1 < size; i++){ //check if temp is larger than array values
if(temp > a[i] && temp < a[i-1]){
for(j = size-1; j >= i; j--) //slide down the rest of the array
a[j] = a[j-1];
a[i] = temp;
}
}
}
for(i=0; i <size; i++){ //print out array
printf("%d ", a[i]);
}
return (0);
}
我已经在更较小的简单技能上尝试了这一点,因为我已经创建了数组和值,而不是使用用户输入。我还刚刚通过一个循环将数组检查序列传递,该循环增加了数字值,而不是从文件中读取。这似乎可以与
之类的东西一起工作a[5] = {10, 8, 6, 4, 2};
number = 5; // number++ number = 6 number = 7... until 10
result: a[5] = {10, 9, 8, 7, 6};
我很遗憾地说,即使程序在开始时没有打印正确的数组,我也可以看到文件中有数字。循环仍在陷入文件,但在某一时刻,输出刚刚开始是分类的用户数组。我似乎无法正确获得数组值。有什么想法吗?
昨天继续从我的评论中继续,如果错误是由于您的代码重新计算引起的,但这是您想像乔纳森(Jonathan)指出的那样剪切和粘贴的全部原因 - 消除转录过程中的人为错误。
我想我理解您的主要问题是什么。如果您的目标是从stdin
读取一些数量的用户输入值,请按顺序排序,然后打开一个文件,然后以分类订单读取单个附加值,则必须为最终值提供空间您在声明时(如果使用VLA)时的数组。否则,您要么需要创建一个足够大的VLA以存储使用和文件中的值,然后将用户复制到新数组中提供的值,或者最初动态分配数组(使用malloc
或calloc
),然后根据需要进行realloc
根据需要添加空间。
在这种情况下,这并不困难,因为您知道自己正在从文件中读取一个值。只需从命令行参数读取size
,然后将您的数组创建为int a[size + 1];
您的其余任务可以通过几种方式处理。阅读(和 validate )用户输入后,您可以按降序排序您的值,从文件中读取值,然后创建 insert&amp;Shuffle 例程以正确的顺序插入值并将剩余的数组元素向下移动,>或(可能是错误的错误方法)只是为了将元素从文件添加到末端阵列的,然后再次致电您的sort
例程。
(注意:您应该习惯于使用qsort
,而不是尝试重新发明气泡 - 派,等等。它是更有效的命令,并且较小的错误容易容易出现)
您需要限制(或消除)使用atoi
,因为它提供了零错误检查。一种更好的方法是使用strtol
,然后检查errno
,然后对原件检查 em> END-POINTER 以确定是否读取了任何数字。在一个简单的辅助功能下面包含了strtol
的错误检查以确保您具有size
的实际值。
此外,请小心。尽管您可能希望用户输入size
整数值,但不能保证它们会。最好跟踪实际输入的值的数量,并在随后的迭代中使用该值,而不是在代码的其余部分中盲目迭代for (i = 0; i < size; i++)
。
是否尝试从文件中读取值的现场插入,还是只将其添加到数组的末端,然后再次调用您的排序例程取决于您。我鼓励您将排序代码移至一个函数中,以提供该灵活性,而无需在main
中复制代码。查看以下内容,让我知道您是否有任何疑问。由于我认为这是一个家庭作业,因此下面显示了插入案例(但简单的文件值将文件值添加到末端,然后再次调用SOTE代码,包括评论)
#include <stdio.h>
#include <stdlib.h> /* for strtol */
#include <limits.h> /* for LONG_MAX/MIN */
#include <errno.h> /* for ERANGE,errno */
void sort_int_array_dec (int *a, size_t size);
long xstrtol (char *p, char **ep, int base);
int main (int argc, char **argv) {
/* read size as first argument, or 5 if none given */
int size = argc > 2 ? (int)xstrtol (argv[2], NULL, 10) : 5,
a[size + 1], /* variable length array for user + file values */
n = 0, /* number of values from user */
fval, /* value read from file */
temp, /* temporary value for array */
i = 0;
FILE *fp = NULL;
if (size < 1) return 1;
printf ("enter %d integersn", size);
while (n < size) { /* read up to size values */
int result, c;
printf (" integer[%2d] : ", n + 1);
/* validate read of each value using scanf return */
if ((result = scanf ("%d", &temp)) != 1) {
if (result == EOF) { /* always check for EOF */
fprintf (stderr, "user canceled input.n");
break;
}
fprintf (stderr, "error: invalid conversion.n");
/* empty input buffer of invalid entry */
while ((c = getchar()) != 'n' && c != EOF) {}
}
else /* good value read, save, increment n */
a[n++] = temp;
}
sort_int_array_dec (a, n); /* sort a */
printf ("nsorted array before inserting value from file:nn");
for (int i = 0; i < n; i++)
printf ("a[%2d]: %dn", i, a[i]);
if (!(fp = fopen (argv[1], "r"))) {
fprintf (stderr, "error: file open failed '%s'n", argv[1]);
return 1;
}
if (fscanf (fp, "%d", &fval) != 1) { /* read value from file */
fprintf (stderr, "error: read of file value failed.n");
return 1;
}
printf ("n value from file: %dnn", fval);
/* add fval into array in descending sort order
* (you can add it anywhere and simply call sort again, e.g.)
*/
// a[n] = fval; /* add it to the end of the array */
// sort_int_array_dec (a, n + 1); /* sort a again */
for (i = 1; i < n + 1; i++) {
if (fval > a[i-1]) {
temp = a[i-1];
a[i-1] = fval;
break; /* temp now holds value to insert at i */
}
}
if (i == n + 1) /* if already at last element just set it */
a[n] = fval;
else /* otherwise, insert and shuffle remaining elements down */
for (int j = i; j < n + 1; j++) {
int mov = a[j];
a[j] = temp;
temp = mov;
}
printf ("sorted array after inserting value from file:nn");
for (int i = 0; i < n + 1; i++)
printf (" a[%2d]: %dn", i, a[i]);
return 0;
}
/** sort integer array descending (your code) */
void sort_int_array_dec (int *a, size_t size)
{
size_t i, j;
int temp;
if (size < 2) return; /* nothing to sort */
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (a[i] < a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
/** a simple strtol implementation with error checking.
* any failed conversion will cause program exit. Adjust
* response to failed conversion as required.
*/
long xstrtol (char *p, char **ep, int base)
{
errno = 0;
char *endpt = ep ? *ep : NULL;
long tmp = strtol (p, &endpt, base);
/* Check for various possible errors */
if ((errno == ERANGE && (tmp == LONG_MIN || tmp == LONG_MAX)) ||
(errno != 0 && tmp == 0)) {
perror ("strtol");
exit (EXIT_FAILURE);
}
if (endpt == p) {
fprintf (stderr, "No digits were foundn");
exit (EXIT_FAILURE);
}
if (ep) *ep = endpt;
return tmp;
}
示例使用/输出
$ cat dat/file.txt
523
$ ./bin/addintoarray dat/file.txt 4
enter 4 integers
integer[ 1] : 400
integer[ 2] : 500
integer[ 3] : 600
integer[ 4] : 700
sorted array before inserting value from file:
a[ 0]: 700
a[ 1]: 600
a[ 2]: 500
a[ 3]: 400
value from file: 523
sorted array after inserting value from file:
a[ 0]: 700
a[ 1]: 600
a[ 2]: 523
a[ 3]: 500
a[ 4]: 400
/*I'm a beginner C programmer so I don't know much of the syntax.
But I think I can help you with that problem.
I created a simple code and I hope I can really help
the integers from the file must be already sorted.
So the only integer that we will sort is the recent integer that the user inputed.
*/
/*So here's my code of sorting array of integers coming from file.
Please give it a try.
It's not the same syntax as your code but I know you can see my point*/
#include <stdio.h>
#include <stdlib.h>
//my style here is I'm declaring the max Num that I want to put in array.
//But you can do this with different style.
#define MAX_ARRAY 10
//I created separate functions
void readFile(int num_arr[]);
void sortArray(int num_arr[]);
void writeFile(int num_arr[]);
int main()
{
int num_arr[MAX_ARRAY + 1]; // take note that I added 1 (one). And you will see later why I did that
readFile(num_arr);
sortArray(num_arr);
writeFile(num_arr);
//Now we can sort them. Use a temp_num holder.
return 0;
}
void readFile(int num_arr[])
{
int x = 0;
int y = 0;
int temp_num;
FILE *sample_file_pointer = fopen("sample_file.txt", "r");
//first I read the integers from the file and put them in int array.
while(fscanf(sample_file_pointer, " %dn", &num_arr[x]) == 1)
{
x++;
}//after reading the integers, the last element of the array we declared is still unused.. Now we will use it.
fclose(sample_file_pointer);
//now we will use the unused element by entering the 'n'. Then we will sort the array later.
printf("Enter value of n: ");
scanf(" %d", &num_arr[MAX_ARRAY]);//We put the n value in the last element of the array
}
void sortArray(int num_arr[])
{
int x = MAX_ARRAY;//We will use this to point the last element of the array.
int temp_num;
/*because the array from
the file is already
sorted, (I know you can
do the sorting of that.
That's why I didn't include
it here to make this short)
we can just test the most recent
integer that is added by the user*/
//We do that with this loop
for(int i = MAX_ARRAY; i > 0; i--)
{
if(num_arr[x] >= num_arr[i - 1])
{
temp_num = num_arr[x];
num_arr[x] = num_arr[i - 1];
num_arr[i - 1] = temp_num;
//now set the x to the swapped element to follow the recent number all through. Till the element test becomes 1.
x = i - 1;
}
}
//now we're ready to write this sorted array to a file again
}
void writeFile(int num_arr[])
{
FILE *sample_file_pointer = fopen("sample_file.txt", "w");
for(int i = 0; i < MAX_ARRAY; i++)
{
fprintf(sample_file_pointer, "%dn", num_arr[i]);
}
//We can ignore the last element of the array. She's out of the group now. It's her fault for being the lowest.. LOL..
fclose(sample_file_pointer);
}