简体   繁体   中英

Function that stores string including tabs,spaces and new lines in C

I wanted to store a string up to n characters including tabs,spaces and new line chars but i can't understand how to get this '\0' char only at the end of the string.

void takeString(char *c,int n)
{
    int i=0;
    char *result = fgets(c,n,stdin);
    if(result)
    {
        while(c[i] != '\0')
            i++;
        if(c[i]=='\0')
            c[i] = ' ';
    }
    c[n] = '\0';
}

but i can't understand how to get this '\0' char only at the end of the string.

if(c[i]=='\0') c[i] = ' '; causes c[] to no longer be a string as it lacks a null character .

c[n] = '\0'; has 2 problems. It does not make c[] a string again as it is not setting the character after the ' ' and 2) it is likely setting a character outside the array pointer to my c resulting in undefined behavior (UB).

Instead, after c[i] = ' ' , set the next character to '\0' .

It remains unclear why OP wants to append a space character.

void takeString(char *c, int n) {
    int i=0;
    //char *result = fgets(c,n,stdin);
    char *result = fgets(c,n-1,stdin); // Leave room to append a ' '
    if(result) {
        while(c[i] != '\0') {
            i++;
        } 
        //if(c[i]=='\0')
        c[i++] = ' ';
        c[i] = '\0';
    }
    // c[n] = '\0';
}

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