0

I have created a little script in C which displays text in a Linux console, but I found one problem - the script adds a line break at the end of text. I have no idea why, normally I should get line break after /n.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char buf[1024];
    char txt[100];
    printf("Insert a text: ");
    fgets(txt, 100, stdin);
    snprintf(buf, sizeof(buf), "echo '%s'", txt);
    system(buf);
}

The structure of the code has to stay the same. I need to use system function and snprintf().

I want to make a few things clear. Right when I'm running this script the output looks like this:

root@test:/home# ./app
Insert a text: Hello
Hello

root@test:/home#

How can I remove this newline after Hello?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt
  • 7
  • 5

2 Answers2

1

fgets consumes the \n character in the buffer which you press after entering data. Just add

txt[strcspn(txt,"\n")] = 0;

just after the fgets to replace the \n character at the end of txt with a NUL-terminator. The strcspn function, in your case, counts the number of characters in txt until a \n character. If no newline character is found, then it returns the length of txt(strlen(txt)).

BTW, you need to include string.h if you want to use this function:

#include <string.h>
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • I'm getting : app.c: In function ‘main’: app.c:9:5: warning: incompatible implicit declaration of built-in function ‘strcspn’ [enabled by default] txt[strcspn(txt,"\n")] = 0; ^ – Matt May 08 '15 at 09:46
  • Oh. I forgot to mention that you need to include `string.h` for using this function. – Spikatrix May 08 '15 at 09:47
  • THANK YOU !! Everything is working now how it should be! – Matt May 08 '15 at 09:49
0

The problem you're facing is related with how fgets() behave. As per the man page

char *fgets(char *s, int size, FILE *stream);

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

So, it reads and stores the trailing \n (newline) generated by pressing ENTER after the input into txt. If you don't want that \n to be present in txt, you need to remove that from the input buffer manually before printing the contents of txt.

You can use strchr() or strcspn() to find out the possible \n and replace that with \0 (null) to solve your issue.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261