简体   繁体   中英

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

"

在此输入图像描述

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

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM