[英]How to read both from user input and txt file - C Console
我有一個程序,用戶輸入一個由逗號分隔的實數對列表,然后該程序將計算它的平均值、中位數、眾數、計算數據的數量等......
到目前為止,它可以很好地讀取用戶輸入。 我只是想知道有沒有辦法讓程序也從 .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
輸入,正如您所說的那樣。 傳遞給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
參數,即可從命令行中指定的文件中提取輸入
給你的評論:
抱歉回復慢。 文檔是關於fopen_s()
,這是fopen()
的“更安全”版本。
errno_t fopen_s(
FILE** pFile,
const char *filename,
const char *mode
);
基本上,語法有點不同。 不是將FILE
指針設置為返回值,而是將指向該指針的指針作為第一個參數傳遞。 用法如下:
FILE *file_ptr;
errno_t check_this = fopen_s(&file_ptr, filename, mode);
如果您需要有關傳遞指針到指針的工作原理的更多信息,請詢問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.