[英]How to read from a .txt file in a C Console Program?
我有一個程序,我必須從用戶輸入中讀取數據以獲取數據對列表,例如:
1,2 3,4 5,6
或者:
1,2
3,4
5,6
4,3
這是我的代碼
#include <stdio.h>
#include <stdlib.h>
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 n1, n2;
int x[10] = { 0 };
int y[10] = { 0 };
int capacity = 0;
int n = sizeof(x) / sizeof(x[0]);
for (size_t i = 0; i < n; ++i)
{
scanf_s(" %d , %d [^\n]", &n1, &n2);
x[i] = n1;
y[i] = n2;
}
for (int 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 中運行命令將文件通過管道傳輸到控制台時: program.exe some.txt
它會給我:
-858993460 , -858993460
-858993460 , -858993460
...
但是當我輸入 txt 文件中的值時,我得到了正確的輸出。
有沒有讓 C 控制台程序接受用戶輸入和 .txt 文件?
我的教授展示了一個使用 scanf_s 的例子,他可以只使用 debug.exe 和 txt 文件來獲取輸入,他說這會欺騙程序認為它來自鍵盤緩沖區。 我對這將如何工作感到困惑。
來自 CMD 的錯誤代碼:
C:\\Users\\username\\Downloads\\Project\\test_files>sort.exe book.txt -> sort.exe < book.txt
該進程無法訪問該文件,因為它正被另一個進程使用。
另一個錯誤是一個紅色的彈出窗口,說我應該得到一個最終版本(它是從窗口彈出的)。
你的命令行是錯誤的。
代替:
sort.exe < book.txt -> sort.exe < book.txt
你要:
sort.exe < book.txt | sort.exe > book2.txt
但無論如何,我不確定你到底想在這里做什么......
請注意,您需要另一個文件book2.txt
而不是book.txt
,這就是The process cannot access the file because it is being used by another process.
錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.