Home > front end >  get string in input and print it folded in C
get string in input and print it folded in C

Time:10-05

I'm trying to write a program which gets one or more input lines, and if one line is too long, it gets folded at a maximum number of chars. My approach would be to write the input chars in a first array, of a given length. If Maximum length is reached or '\n' as input, i copy the content in a bigger array which will be the final string to print and get the second line in input. Problem is: it doesn't work and I can't figure out why. Thanks for the help

#include <stdio.h>
#define MAXCOL 10
#define FINAL_LENGTH 300
char line[MAXCOL];
char final_string[FINAL_LENGTH];
extern int fnlstr_pos = 0;
int main() 
{
    int pos, c;
    pos = 0;
    while(c=getchar() != EOF)
    {
        line[pos] = c;

        if (pos   1 >= MAXCOL || c == '\n'){
            to_printandi(pos);
            pos = 0;
        }
          pos;

    }
    printf("%s", final_string);


}


to_printandi(pos)
int pos;
{
    int i;
    for(i = 0; i <= pos;   i){
        final_string[fnlstr_pos] = line[i]; 
          fnlstr_pos;
    }
    if (final_string[fnlstr_pos] != '\n'){
        final_string[  fnlstr_pos] = '\n';
    }
      fnlstr_pos;
}

CodePudding user response:

For starters this statement

while(c=getchar() != EOF)

is equivalent to

while( c = ( getchar() != EOF ) )

So c is always equal to1 if EOF is not encountered.

You need to write

while( ( c=getchar() ) != EOF)

And you need to append the input sequence with the terminating zero character '\0' tp form a string.

Another problem is these code snippet with for loop

for(i = 0; i <= pos;   i){
    final_string[fnlstr_pos] = line[i]; 
      fnlstr_pos;
}

As within the loop the variable fnlstr_pos was increased then this if statement

if (final_string[fnlstr_pos] != '\n'){
    final_string[  fnlstr_pos] = '\n';
}

invokes undefined behavior because the variable points to a non-initialized element of the array.

CodePudding user response:

This question is very broad and it would helpful if you said what the problem is but I can see one issue -- you don't null terminate the final_string variable. add

final_string[fnlstr_pos] = '\0';

before the printf.

Maybe that fixes the problem you are having.

CodePudding user response:

The main problem is here:

while(c=getchar() != EOF)

Given the operator precedence, this will result in the same as:

while(c= (getchar() != EOF))

So c will be 1 (true) inside the loop.

Change this to:

while((c=getchar()) != EOF)

This is the main problem. Just as @Hogan suggested, there are other issues such as not null terminating the strings. As you declare them global, they will be zeroed so you can get away with that though not in the case the user provides a string with maximum length.

Also it would greatly improve the code if you could use string manipulation functions from <string.h> instead of copying byte by byte.

  • Related