如何在C控制台程序中读取.txt文件?
我有一个程序,在该程序中,我必须从用户输入中读取数据以获得数据对列表,例如:如何在C控制台程序中读取.txt文件?,c,file,console,user-input,C,File,Console,User Input,我有一个程序,在该程序中,我必须从用户输入中读取数据以获得数据对列表,例如: 1,2 3,4 5,6 或: 这是我的密码 #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 = a
1,2 3,4 5,6
或:
这是我的密码
#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;
}
但是,当我在中键入txt文件中的值时,我得到了正确的输出
是否有任何方法可以让C控制台程序接受用户输入和.txt文件
我的教授展示了一个使用scanf_s的例子,他可以使用debug.exe和txt文件来获取输入,他说这会让程序误以为它来自键盘缓冲区。
我对这将如何工作感到困惑
CMD中的错误代码:
C:\Users\username\Downloads\Project\test\u files>sort.exe book.txt->sort.exe另一个错误是一个红色的弹出窗口,上面说我应该获得最终版本(这是一个来自windows的弹出窗口)。您的命令行错误 而不是:
sort.exe < book.txt -> sort.exe < book.txt
sort.exesort.exe
你想要:
sort.exe < book.txt | sort.exe > book2.txt
sort.exebook2.txt
但不管怎样我不知道你到底想在这里做什么
请注意,您需要另一个文件
book2.txt
,而不是book.txt
,这就是进程无法访问该文件的原因,因为它正被另一个进程使用。
错误。program.exe some.txt
->program.exe
我被拒绝访问/其他进程正在使用错误请显示verbatin错误消息以及您在cmd中键入的逐字命令。[Edikt]请回答您的问题,并将所有相关信息放在那里。还可以通过添加#includes将代码转换为。我提供了我的代码和收到的错误消息。请看一看并阅读。你的文章包含足够的源代码,我们可以编译它。如果您告诉我们如何编译和链接它,它也会有所帮助。您到底希望扫描什么(“%d,%d[^\n]”、&n1和&n2)代码>要做什么?
sort.exe < book.txt -> sort.exe < book.txt
sort.exe < book.txt | sort.exe > book2.txt