c - 如何解析用户的输入以确定在 C 中打印结果的位置?

标签 c io

问题:用户应该能够选择她/他想要生成多少个句子,并选择将输出打印到文本文件或终端屏幕(输入示例:4 c.txt),因此如果用户没有选择文件名,那么输出应该显示在终端上。

但是,我无法找到解决这两个问题的方法。

1- 如何从输入中解析 inNum 和文件名(str)。

2-允许用户选择在文本文件中打印输出或在终端中打印输出。

这是我的C语言代码:

FILE *fileptr;
char str[50];
printf("Enter # then str:\n");
scanf("%d %s",&inNum,&str);    
fileptr = fopen(str, "w");
if(fileptr == NULL)
{
  for(n=0;n<inNum;n++)
    {
        printf("%s %s %s %s %s %s\n",article[rand()%5],noun[rand()%5],verb[rand()%5],preposition[rand()%5],article[rand()%5],noun[rand()%5]);
    }
}
else
{
    for(int n=0;n<inNum;n++)
    {
        fprintf("%s %s %s %s %s %s\n",article[rand()%5],noun[rand()%5],verb[rand()%5],preposition[rand()%5],article[rand()%5],noun[rand()%5]);
    }
}
fclose(fileptr);

return 0;

最佳答案

写入命名文件或stdout(默认情况下,如果没有给出输出文件名)相对容易。关键是将完整的输入行作为单行读取并使用 sscanf 进行解析,而不是尝试使用 scanf 进行读取(如果输入是,这将阻止等待输入)缺失)

读取用户输入时,不要吝惜缓冲区大小。对于输入行,使用一些合理的大小 1024 左右。如果您可以保证名称永远不会超过 49 个字符,则可以将输入和输出文件名的大小设置为 50,否则包括 limits.h 和使用宏PATH_MAX来调整文件名缓冲区的大小,这将保证有足够的大小来容纳系统可接受的最大文件名。

(记住:您希望缓冲区为 10,000 个字符太长,而不是 1 个字符太短)

记住,您可以执行类似以下操作,它至少需要用户给出行数和输入文件名,并将写入输出文件名(如果给定),否则它将把行写入默认情况下stdout:

#include <stdio.h>

#define MAXC   50   /* if you need a constanst, #define one (or more) */
#define MAXB 1024   /* size of read buffer (don't skimp!) */

int main (void) {

    char buf[MAXB] = "",    /* buffer to hold lines read */
        ifn[MAXC] = "",     /* input filename */
        ofn[MAXC] = "";     /* output filename */
    FILE *ifp = NULL,       /* in file pointer */
        *ofp = stdout;      /* out file pointer (initialized to stdout) */
    int n = 0,              /* number of lines to display */
        cnt = 0,            /* count of lines output */
        rtn = 0;            /* sscanf return */

    printf ("enter # then filename [outfile (stdout)]: ");
    if (!fgets (buf, MAXB, stdin)) {    /* read complete line of input */
        fputs ("user canceled input.\n", stderr);
        return 1;
    }
    /* parse line of input into n, ifn, and ofn */
    rtn = sscanf (buf, "%d %s %s", &n, ifn, ofn);

    if (rtn < 2) {  /* if not n and infile name, handle error */
        fputs ("error: insufficient input.\n", stderr);
        return 1;
    }

    if (!(ifp = fopen (ifn, "r"))) {    /* open infile/validate open */
        perror ("fopen-str");
        return 1;
    }

    if (rtn == 3) {     /* if outfile provided, open/validate open */
        if (!(ofp = fopen (ofn, "w"))) {
            perror ("fopen-ofn");  /* show error, write to stdout (default) */
            fputs ("warning: writing to stdout by default.\n", stderr);
        }
    }

    while (cnt < n && fgets (buf, MAXB, ifp)) { /* read up to n lines */
        fputs (buf, ofp);   /* output to ofp (which can be stdout) */
        cnt++;              /* increment line count */
    }

    fclose (ifp);           /* close input file */
    if (ofp != stdout)      /* if output file not stdout */
        if (fclose (ofp) == EOF)    /* validate close-after-write */
            perror ("fclose(ofp)"); /* to catch stream and unreported err */

    return 0;
}

输入文件示例

$ cat dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.

示例使用/输出(默认为 stdout)

$ ./bin/outputnlines
enter # then filename [outfile (stdout)]: 3 dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave

示例使用/输出到文件

$ ./bin/outputnlines
enter # then filename [outfile (stdout)]: 3 dat/captnjack.txt dat/cjout3.txt

文件内容

$ cat dat/cjout3.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave

仔细检查一下,如果有疑问请告诉我。

关于c - 如何解析用户的输入以确定在 C 中打印结果的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52808468/

相关文章:

c - VS 代码中的 "cannot open source file "vcruntime_string.h "(dependency of "string.h ")"

c - reshape() 函数在 glut 中有什么用?

c - 尝试在C中使用宏

java - ObjectInputStream.GetField 和 ObjectOutputStream.PutField

c++ - 无法在 C++ 中读取带有西里尔路径的文件

c - Windows 下 feof() 的奇怪行为

C:如何从函数返回单独的多个值到主函数

java - Java 在文件中间写入的最佳方式

io - Perl6 : run command as a different user

file - 平滑运算符 : Rename a file while writing to it