How to truncate characters over a certain length in C?

932 Views Asked by At

I'm working on a C program that takes in an input of lines of text, and return it by printing only 40 characters each. So far, I have this code:

#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;
}

Just updated my post with a new draft I have. For this attempt I am trying to print each character as it takes each input but if the character count is over 40, to make a new line. But, I don't get an output as expected.

5

There are 5 best solutions below

1
alex01011 On

I'm not sure if thats whats you're asking. Basically every 40 characters, a newline character is printed.

#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;
}

Edit:

Your code seem to work fine if you were to initiliaze numChar --> numChar = 0 and total --> total = 0.

0
Vlad from Moscow On

You are using two uninitialized variables

int numChar;
int total;

So the program has undefined behavior.

Moreover the accumulated value of the variable total is not used in the program.

And the variable input has to be declared as having the type int.

Pay attention to that the last outputted substring can contain less than 40 characters. In this case you need to call

putchar( '\n' );

also after the loop.

Using your approach with inputting characters by means of the function getchar the program can look the following way

#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;
}

If to input the string shown in your question then the output will be

This line is soooooooooooooooooo looooou
oooooooooooooooooooooooooooooooooooooooo
oooong!
0
B. Sebastiano On

Actually strings are sequences of chars terminated by a null char '\0', so strings are arrays of chars.

You can easily iterate over the string untill you encounter the null char and on every iteration you print the current char and if the character index is a multiple of 40 you print a new line char, in this way every 40 character you split the string.

So here is the code:

#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');
        }
    }
}
0
anotherOne On
#include <stdio.h>

int main() {

    char c;

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

Or if you want to avoid starting on a newline , just change the if to

if( i && !(i % 40) ) puts("");
6
chqrlie On

There are multiple problems:

  • numChars and total are uninitialized, you get undefined behavior.
  • you only handle the first line of text as you stop when you read a newline.

Here is a modified version:

#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;
}