简体   繁体   中英

Concatenating a char into a string

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, s for example, string becomes a%Ts%T )

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

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] = '\0';
        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 Enter it still doesn't work. It keep entering the loop and if.

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

c[0] = getche();

to

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

and worked awesomely well.

Ok here is the solution

 strcat(string, &c);

change this to

strncat(string, &c,1);

now the answer to the question why ?

well first of call the below statement

c = getche();

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

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

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

now to the next important statement

strcat(string, &c);

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.

I hope it's clear now...

PS - if you have access to gdb you can check practically..

1) you should initialize

int x=1;

2) you should update this line:

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

to

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

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

strcat(string, &c);

use the following lines

string[x-2] = c;
string[x-1] = '\0';
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] = '\0';
            break;
        }
    }

    return string;
}

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