0

I need to read from user some text and then print out the same text, with " at the beginning and " at the end of the string. I used getline to read a whole line (with spaces too).

Example (what I should get):

User writes: hello

I need to print: "hello"

Example (what Im getting):

User writes: hello

My app prints: "hello

"

enter image description here

My code:

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

void fun(int times)
{
    int i = 0, j = 255;
    char *str = malloc(sizeof(char) * j);
    char *mod = malloc(sizeof(char) * j);
    for(i=0; i<j; i++)
        mod[i] = 0;

    i = 0;

    while(i<times)
    {
        printf("\n> ");
        getline(&str, &j, stdin);

        strcpy(mod, "\"");
        strcat(mod, str);
        strcat(mod, "\"");

        printf("%s\n", mod);

        i ++;
    }

    free(mod);
    mod = NULL;
    free(str);
    str = NULL;
}

int main(int argc, char **argv)
{

    fun(4);

    return 0;
}

SOLVED:

Hah, it was easy .. But can it be done EASIER?

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

void fun(int times)
{
    int i = 0, j = 255;
    char *str = malloc(sizeof(char) * j);
    char *mod = malloc(sizeof(char) * j);
    for(i=0; i<j; i++)
        mod[i] = 0;

    i = 0;

    while(i<times)
    {
        printf("\n> ");
        getline(&str, &j, stdin);

        int s = strlen(str);

        strcpy(mod, "\"");
        strcat(mod, str);
        mod[s] = 0;
        strcat(mod, "\"");

        printf("%s\n", mod);

        i ++;
    }

    free(mod);
    mod = NULL;
    free(str);
    str = NULL;
}

int main(int argc, char **argv)
{

    fun(4);

    return 0;
}
yak
  • 3,770
  • 19
  • 60
  • 111
  • Easier: `getline(&(str+1), &j, stdin)`. Also loose the 'init-to-zero' for your `mod` string -- in fact, you don't need `mod` at all. – Jongware Jan 19 '14 at 12:08

2 Answers2

1

This is because getline is consuming the newline character entered in the input. You have to manually remove the newline from str before concatenating it to mod.

Use strlen to get the length of the input and put a '\0' in place of '\n', then add it to mod.

Dipto
  • 2,720
  • 2
  • 22
  • 42
1

Use getline() return value, char assignments and memcpy().

// Not neeeded
// for(i=0; i<j; i++) mod[i] = 0;

ssize_t len = getline(&str, &j, stdin);
if (len == -1) Handle_Error();
if (len > 0 && str[len - 1] == '\n') {
  str[--len] = '\0';
}
mod[0] = '\"';
memcpy(&mod[1], str, len);
mod[len + 1] = '\"';
mod[len + 2] = '\0';
printf("%s\n", mod); 

Note: Should insure mod is big enough by realloc() after determining len.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256