【问题标题】:How do I get the input to cut off or wrap around at a certain point?如何让输入在某个点被切断或环绕?
【发布时间】:2012-12-07 00:21:42
【问题描述】:

好的,所以在使用了一天的 stackoverflow 之后,我了解到在这个站点上是很有用的 :) 我最终让我的程序运行起来。我可以在命令行中获取无限数量的文本文件并显示它们!所以它看起来像这样:


CMD 控制台

c:\Users\Username\Desktop> wrapfile.exe hello.txt how.txt。 are.txt you.txt random.txt

你好,你今天好吗?我希望你做得很好。这只是一个测试,看看我能在屏幕上放多少。


现在,我想在这个程序上进行构建。我将如何让这个新发现的文本环绕?比如,如果你想让它每 40 个字符左右,文本跳到下一行……我们怎么能做这样的事情?

再次感谢!

这是我正在使用的代码:

#include <stdio.h>
#include <stdlib.h>


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

    int l = 1;
        while(l != argc)
{
        FILE *fp; // declaring variable


        fp = fopen(argv[l], "rb");
        l++;


    if (fp != NULL) // checks the return value from fopen
    {
        int i = 1;
        do
        {
            i = fgetc(fp);     // scans the file 
            printf("%c",i);
            printf(" ");
        }
        while(i!=-1);
        fclose(fp);
    }
    else
    {
        printf("Error.\n");
    }
}


}

【问题讨论】:

  • 你试过什么?看起来您只想每 40 个字符打印一个换行符。
  • 我的建议,实现一个字符计数器,每 40 个字符重置一次,然后插入一个换行符。
  • 嗯,我想尝试将文本文件放入一个字符串中,然后扫描该字符串,每 40 个字符添加一个 \n。这可能听起来很野蛮哈哈,但我是 C 的新手,我只是想在明年 9 月开学前学习一些新方法:p

标签: c text console cmd


【解决方案1】:

好的,我们开始吧...这看起来和你的有点不同,但这是 ISO/ANSI C 1989 标准。

int main(int argc, char **argv)
{
     FILE *fd = NULL;
     char linebuf[40];
     int arg = 1;

     while (arg < argc) {
         fd = fopen(argv[arg], "r");
         if (NULL != fd) {
              /* fgets(char *buf, size_t buflen, FILE *fd): returns NULL on error. */
              while (NULL != fgets(linebuf, sizeof(linebuf), fd)) {
                  printf("%s\n", linebuf);
              }
              fclose(fd);
         } else {
              fprintf(stderr, "Cannot open \"%s\"\n", argv[arg]);
         }
         ++arg;
     }
 }

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 2021-08-31
    相关资源
    最近更新 更多