0
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(){
    char storage[128]="\0";
    char buffer[24];
    fgets(buffer, 24, stdin);
    strcat(storage, buffer);
    fgets(buffer, 24, stdin);
    strcat(storage, buffer);
    printf("%s", storage); // line 12
    return 0;
    }

I am trying to see that line 12 prints "string one\0string two" when I enter "string one" and "string two" on previous fgets() lines but instead, it prints "string one\nstring two". As far as I know strcat() terminates the "\0" at the end of the first string so this code should have given me the format I wanted, but it does not. What am I doing wrong?

Deniz
  • 509
  • 7
  • 26
  • 1
    `char storage[128]="\0";` --> `char storage[128]="";` the string terminator will be added by the compiler. – Weather Vane Nov 26 '15 at 17:18
  • @WeatherVane I have updated my code in the way you suggested and I am still having the same behavior. – Deniz Nov 26 '15 at 17:19
  • 2
    Do you mean it still prints `"string one\0string two"` after making the change I suggested? Note that `fgets()` retains the `newline` at the end, is that what you are seeing? – Weather Vane Nov 26 '15 at 17:21
  • @WeatherVane What I want is `"string one\0string two"`, but it gives me `"string one\nstring two"`. So, after I made the change you suggested, it still gave me `"string one\nstring two"`. At least that's what I'm seeing on the screen, basically string one printed on one line and string two is on the next line as if there were a `"\n"` inbetween. – Deniz Nov 26 '15 at 17:24
  • 1
    You can remove the trailing newline retained by `fgets()` like this: it is safe even when there is no newline present. `buffer [ strcspn(buffer, "\r\n") ] = 0;` However you will get `"string onestring two"` and not `"string one\0string two"`. – Weather Vane Nov 26 '15 at 17:30
  • @WeatherVane Thank you for the tip. I was planning to use `buffer[strlen(buffer)-1]=0;` but not sure which one would work better. I'll try it both ways. Add: Just found out `strlen()` doesn't work good when the input string fills the buffer completely. So I guess I'm going with `strcspn()`. Thank you. – Deniz Nov 26 '15 at 17:37

1 Answers1

1

The result "string one\nstring two" is correct because the newline is read by fgets. You input the newline when you press enter to end the input.

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

this
  • 5,229
  • 1
  • 22
  • 51