如何在C中截断一定长度的字符?

问题描述

我正在开发一个 C 程序,该程序接受输入的文本行,并通过每行仅打印 40 个字符来返回它。 到目前为止,我有这个代码:

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

int main() {
    char input = getchar();
    int numChar;
    int total;

    while ((input != EOF) && (input != '\n')) {
        ++numChar;
        if (numChar > 40) {
            printf("\n");
            ++total;
            numChar = 0;
        }
        putchar(input);
        input = getchar();
    }
    return EXIT_SUCCESS;
}

刚刚用我的新草稿更新了我的帖子。对于这次尝试,我试图打印每个字符,因为它需要每个输入,但如果字符数超过 40,则创建一个新行。但是,我没有得到预期的输出。

解决方法

您正在使用两个未初始化的变量

int numChar;
int total;

所以程序有未定义的行为。

而且程序中没有使用变量total的累加值。

变量 input 必须声明为类型为 int

注意最后输出的子串可以少于40个字符。在这种情况下,您需要调用

putchar( '\n' );

也在循环之后。

使用您的方法通过函数 getchar 输入字符,程序可以如下所示

#include <stdio.h>

int main(void) 
{
    const size_t LINE_LENGTH = 40;
    
    size_t count = 0;
    
    for ( int c; ( c = getchar() ) != EOF && c != '\n'; )
    {
        putchar( c );

        if ( ++count % LINE_LENGTH == 0 )
        {
            putchar( '\n' );
            count = 0;
        }

    }

    if ( count % LINE_LENGTH != 0 ) putchar( '\n' );
    
    return 0;
}

如果输入问题中显示的字符串,则输出为

This line is soooooooooooooooooo looooou
oooooooooooooooooooooooooooooooooooooooo
oooong!
,

我不确定这是否是您要问的。基本上每 40 个字符,就会打印一个 newline 字符。

#include <stdio.h>

int main(void)
{
  int c = 0;
  size_t i = 0;

  while ((c = getchar()) != EOF)
  {
    if (i++ < 40)
    {
      putchar(c);
    }
    else if (i++ > 40 && c !='\n')
    {
      i = 1;
      printf("\n%c",c);
    }
    if (c == '\n')
    {
      i = 0;
    }
  }

  return 0;
}

编辑:

您的代码似乎运行良好如果您要初始化 numChar --> numChar = 0total --> {{1 }}。

,

实际上,字符串是由空字符“\0”终止的字符序列,因此字符串是字符数组。

您可以轻松地遍历字符串,直到遇到空字符,并且在每次迭代时打印当前字符,如果字符索引是 40 的倍数,则打印一个新行字符,这样每拆分 40 个字符字符串。

代码如下:

#include <stdio.h>
#define MAX_LENGHT 200

int main () {
    char input[MAX_LENGHT];
    fgets(input,MAX_LENGHT,stdin);
    
    int index = 0;
    while (input[index++] != '\0') {
        putchar(input[index]);
        if (index % 40 == 0) {
            putchar('\n');
        }
    }
}
,
#include <stdio.h>

int main() {

    char c;

    for(int i = 0; (c = getchar()) != EOF; i++) {
        
        if( !(i % 40) ) puts("");
        
        putchar(c);
    }
    
    return 0;
}

或者,如果您想避免换行,只需将 if 更改为

if( i && !(i % 40) ) puts("");
,

存在多个问题:

  • numCharstotal 未初始化,您会得到未定义的行为。
  • 当您阅读换行符时停止时,您只会处理第一行文本。

这是修改后的版本:

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

int main() {
    int pos = 0,c;

    while ((c = getchar()) != EOF) {
        if (c == '\n') {
            putchar(c);
            pos = 0;
        } else
        if (pos < 40) {
            putchar(c);
            pos++;
        } else {
            // ignore the character beyond the first 40
        }
    }
    return EXIT_SUCCESS;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...