当C中没有命令行参数时,如何获取一组用户输入数字?ISO C17标准



我将以标准作为开场白:我对C编程非常陌生,所以请温和一点。

我正在编写一个C程序,它应该能够将文件路径/文件名作为命令行参数,否则,它应该接受用户输入。我有argv[1]文件名,但如果用户不添加文件名作为arg,我不知道如何将其切换到stdin。输入应该是原始数据,而不是文件名。这是我(非常新手(的代码。作为一名新程序员,我可能需要一些解释,我对此提前道歉。

int main(int argc, char* argv[]) {

#ifndef NDEBUG
printf("DBG: argc = %dn", argc);
for (int i = 1; i < argc; ++i)
printf("DBG: argv[%d] = "%s"n", i, argv[i]);
#endif
FILE* stream = fopen(argv[1], "r");

char ch = 0;
size_t cline = 0;

char filename[MAX_FILE_NAME];
filename[MAX_FILE_NAME - 1] = 0;


if (argc == 2) {
stream = fopen(argv[1], "r");
if (stream == NULL) {
printf("error, <%s> ", argv[1]);
perror(" ");
return EXIT_FAILURE;
}
}
else if (argc ==1)

printf("Enter a list of whitespace-separated real numbers terminated by EOF or 'end'n");

//continue with program using user-input numbers 

您的代码过于复杂和错误。你做事的顺序不对。您首先需要检查是否存在参数,并尝试仅在这种情况下打开文件。

你想要这样的东西:

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE* input = stdin;   // stdin is standard input
// so if no arguments are given we simply read
// from standard input (which is normally your keyboard)
if (argc == 2) {
input = fopen(argv[1], "r");
if (input == NULL) {
fprintf(stderr, "error, <%s> ", argv[1]);
perror(" ");
return EXIT_FAILURE;
}
}
else
printf("Enter a list of whitespace-separated real numbers terminated by EOF or 'end'n");
double number;
while (fscanf(input, "%lf", &number) == 1)
{
// do whatever needs to be done with number
printf("number = %fn", number);
}
fclose(input);
}

最新更新