C语言 将一个字符连接成一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16653458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:24:39  来源:igfitidea点击:

Concatenating a char into a string

cstringloopscharconcatenation

提问by Bestknighter

I am trying to read a string from the console. But I want to read it char by char. And I'm having trouble with concatenating the char into the string AND with breaking the loop. Here is the code:

我正在尝试从控制台读取字符串。但我想逐个字符地阅读它。而且我在将字符连接到字符串和打破循环时遇到了麻烦。这是代码:

char* createString(){
    char c;
    char *string;
    int x=0;

    string = (char*) calloc(1, sizeof(char));
    do{
        c = getche();
        if(c != '\n'){
            x++;
            realloc(string, sizeof(char)*x);
            strcat(string, &c);
        };
    }while(c != '\n');
    return string;
};

When I run this code, each concatenation adds 3 chars, instead of just 1. It's like is accessing non-allocated memory... (For example, if I press a, the final string is a%T. Then, if I press another key, sfor example, string becomes a%Ts%T)

当我运行此代码时,每个连接添加 3 个字符,而不仅仅是 1 个。这就像访问未分配的内存......(例如,如果我按下a,最终字符串是a%T。然后,如果我按下另一个键,s对于例如,字符串变为a%Ts%T)

And when I press Enter, it goes into the if and doesn't get out of the loop.

当我按下 时Enter,它会进入 if 并且不会退出循环。

I have no clue of why and what is going on...

我不知道为什么以及发生了什么......



EDIT

编辑



Based on other tries and responses until now, I changed my code and now it's like this:

根据到目前为止的其他尝试和响应,我更改了代码,现在是这样的:

char* digitarString(){
    char c[2];
    char *string;

    string = (char*) calloc(1, sizeof(char));
    do{
        c[0] = getche();
        c[1] = '
c[0] = getche();
'; if(c[0] != '\n'){ strcat(string, c); }; }while(c[0] != '\n'); return string; };

BUT, there are still two issues...

但是,还有两个问题......

  • The code works, but I think that it's writing in non-allocated memory.
  • When I press Enterit still doesn't work. It keep entering the loop and if.
  • 该代码有效,但我认为它是在未分配的内存中写入的。
  • 当我按下Enter它仍然不起作用。它不断进入循环和如果。

Forget about the Enter... I changed it...

忘记Enter......我改变了它......

scanf("%c", &c[0]);

to

 strcat(string, &c);

and worked awesomely well.

并且工作得非常好。

回答by u__

Ok here is the solution

好的,这是解决方案

strncat(string, &c,1);

change this to

将此更改为

c = getche();

now the answer to the question why ?

现在这个问题的答案为什么?

well first of call the below statement

首先调用下面的语句

    c
+-----------+------------+------------+-----------+------------+------------+
|     a     |            |            |           |            |            |
+---------- +----------  +----------  +---------- +--------- - +---------- +  
  x = &c       x+1             x+2            ......

will scan a value for us and will place in variable called c

将为我们扫描一个值并将其放置在名为 c 的变量中

now lets consider the variable is placed in an arbitrary memory location x

现在让我们考虑将变量放置在任意内存位置 x

strcat(string, &c);

now to the next important statement

现在进入下一个重要声明

int x=1;

the second argument above is supposed to be a string means a NULL termination at the end but we can not guarantee that x+1 location is NULL and if x+1 is not NULL then the string will be more than a single character long and it will end up appending all those characters to your original string hence garbage.

上面的第二个参数应该是一个字符串,意味着最后一个 NULL 终止,但我们不能保证 x+1 位置为 NULL,如果 x+1 不是 NULL,那么字符串将超过一个字符长,它最终会将所有这些字符附加到您的原始字符串中,因此是垃圾。

I hope it's clear now...

我希望现在清楚了...

P.S - if you have access to gdb you can check practically..

PS - 如果您可以访问 gdb,您可以实际检查..

回答by MOHAMED

1) you should initialize

1)你应该初始化

realloc(string, sizeof(char)*x);

2) you should update this line:

2)你应该更新这一行:

string = realloc(string, sizeof(char)*x);

to

strcat(string, &c);

3) Yoou do not need for strcat to concatenate. So instead of using

3) 你不需要 strcat 来连接。所以而不是使用

string[x-2] = c;
string[x-1] = '
char* createString(void){
    int c;
    char *string=NULL;
    int x=0;

    while(1){
        c = getche();
        string = realloc(string, sizeof(char)*(x+1));
        if('\n' != c)//input <ctrl+j> or use getchar()
            string[x++] = (char)c;
        else {
            string[x] = '##代码##';
            break;
        }
    }

    return string;
}
';

use the following lines

使用以下几行

##代码##

回答by BLUEPIXY

##代码##