yak
yak

Reputation: 3930

Add some letters before and after string in C

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

Upvotes: 0

Views: 126

Answers (2)

chux
chux

Reputation: 153348

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.

Upvotes: 1

Dipto
Dipto

Reputation: 2738

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.

Upvotes: 1

Related Questions