我有一个程序,用户输入一个用逗号分隔的实数对列表,然后程序将计算它的均值,中位数,众数,对数据数进行计数等。
到目前为止,它很好地读取了用户输入。我只是想知道程序是否也可以从.txt文件读取。因此是一个txt文件,其中包含用逗号分隔的实数对。
代码:
#include <stdio.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; ++i)
printf("%d ", arr[i]);
}
int main(int argc, char* argv[])
{
int n1, n2;
int x[10] = { 0 };
int y[10] = { 0 };
int capacity = 0;
size_t n = sizeof(x) / sizeof(x[0]);
int ch = 0;
for (size_t i = 0; i < n; ++i)
{
scanf_s(" %d , %d ", &n1, &n2);
x[i] = n1;
y[i] = n2;
}
for (size_t j = 0; j < n; ++j)
{
printf("%d , %d\n", x[j], y[j]);
}
quickSort(x, 0, n-1);
printArray(x, n);
printf("Minimum is: %d", x[0]);
printf("Maximum is: %d", x[n-1]);
return 0;
}
[当我尝试使用CMD从程序中读取txt文件时,它给了我很多数字。
-858993460 , -858993460
-858993460 , -858993460
-858993460 , -858993460
-858993460 , -858993460
-858993460 , -858993460
-858993460 , -858993460
-858993460 , -858993460
-858993460 , -858993460
-858993460 , -858993460
我想我必须使用FILE *流或类似的东西,但是我不确定如何使用fscan_s来实现它。
scanf_s
和fscanf_s
之间的区别只是它们从中提取输入的位置,正如您正确地说过的。传递给fscanf_s
的第一个标识符是FILE *
-指向文件流的指针。该文件流通过调用fopen
或通过返回值的变体进行初始化,并获得指针。一旦有了该指针,您只需要将其传递到fscanf_s
。它应该看起来像这样:
FILE *text_file = fopen("C:\Path\To\File.txt", "r"); //"r" == open for reading
if (text_file == NULL) //error in fopen() e.g. you don't have read permission or the file doesn't exist
{
puts("error");
return 1;
}
fscanf_s(text_file, format_string, varargs);
根据您的评论的旁注。仅通过用fopen()
参数替换argv
中文件的路径,从命令行中指定的文件中提取输入是可行的