【发布时间】:2020-06-10 23:19:44
【问题描述】:
我有一个程序,用户输入一个实数对列表,用逗号分隔,然后程序将计算它的平均值、中位数、众数、计算数据数量等...
到目前为止,它可以很好地读取用户输入。我只是想知道程序是否也可以从 .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 来实现它...
【问题讨论】:
-
您可以从文件中重定向输入:
./program_name < filename -
嗯,这似乎有效!但是为什么这行得通,但是当我的证明只使用类似:“program_name filename.txt”并且它会起作用时?
-
因为
<自动更改程序的标准输入以从文件中读取。在没有<的情况下执行此操作需要您在程序中编写代码以使用fopen()打开文件并从中读取而不是标准输入。
标签: c file input console scanf