简体   繁体   English

在C中的字符串前后添加一些字母

[英]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). 我使用getline读取整行(也有空格)。

Example (what I should get): 示例(我应该得到的):

User writes: hello 用户写道: hello

I need to print: "hello" 我需要打印: "hello"

Example (what Im getting): 示例(我得到的):

User writes: hello 用户写道: hello

My app prints: "hello 我的应用打印: "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. 这是因为getline正在消耗输入中输入的换行符。 You have to manually remove the newline from str before concatenating it to mod . 在将其连接到mod之前,必须手动从str删除换行符。

Use strlen to get the length of the input and put a '\\0' in place of '\\n' , then add it to mod . 使用strlen获取输入的长度并将'\\0'替换为'\\n' ,然后将其添加到mod

Use getline() return value, char assignments and memcpy() . 使用getline()返回值,char赋值和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 . 注意:在确定len之后,应该通过realloc()保证mod足够大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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