【问题标题】:Add some letters before and after string in C在C中的字符串前后添加一些字母
【发布时间】:2014-01-19 10:51:20
【问题描述】:

我需要从用户那里读取一些文本,然后打印出相同的文本," 在开头," 在字符串结尾。我用getline 读了一整行(也有空格)。

示例(我应该得到什么):

用户写道:hello

我需要打印:"hello"

示例(我得到了什么):

用户写道:hello

我的应用打印:"hello

"

我的代码:

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

已解决:

哈,这很容易..但是可以更轻松地完成吗?

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

【问题讨论】:

  • 更简单:getline(&amp;(str+1), &amp;j, stdin)。还要为您的mod 字符串松开“初始化为零”——事实上,您根本不需要mod

标签: c getline


【解决方案1】:

这是因为getline 正在使用输入中输入的换行符。在将其连接到 mod 之前,您必须手动从 str 中删除换行符。

使用strlen 获取输入的长度并将'\0' 代替'\n',然后将其添加到mod

【讨论】:

  • hmm.. 我发帖后看到了。
【解决方案2】:

使用getline() 返回值、字符分配和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); 

注意:在确定len后,应通过realloc()确保mod足够大。

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多