简体   繁体   中英

I don't know how to use chars in C

I'm a beginner in programming so I've been making some mini projects. I am trying to make a code that takes a string and returns one in which each character is repeated once and I'm getting an error and these signs (╠╠╠╠╠╠╠╠). Where am I going wrong?

    char str[20], fin[40];
    int i, j=0;

    gets(str);

    while (str[j] != '\0'){
        j++;
    }

    for (i = 0; i < j; i++){
        fin[i*2-1] = str[i];
        fin[i*2] = str[i];
    }

    printf("%s\n", fin);

    return 0;

C does not have strings . Strings , in C, are a convention used by the compiler and the programmer and the Standard Library (and every library ever written). If you break the convention strings no longer "work" even though your code may be correct C code.

Depending on context, a string is a [part of an] array of char that contains a zero byte, or a pointer to such an array, like

char text[3] = {'h', 'i', '\0'}; // text is an array that contains the string "hi"
char *ptr = text;                // ptr points to the string "hi"

When you build your string character-by-character, remember the array elements start as garbage

char fin[20]; // fin is an array of 20 characters.
              // It is capable of holding string of up to 19 characters length
              // and the respective terminator
fin[0] = 'C'; // fin (the whole array) is not a string
fin[1] = '\0'; // fin now is the string "C" with the proper terminator (and a bunch of unused elements

fin[1] = ' '; // replaced the terminator with a space
              // fin is no longer a string
fin[2] = 'i';
fin[3] = 's'; // "C is############garbage########..." not a string
fin[4] = ' ';
fin[5] = 'f';
fin[6] = 'u';
fin[7] = 'n'; // "C is fun########garbage########..." not a string
fin[8] = '.'; // "C is fun.#######garbage########..." not a string
fin[9] = '\0'; // "C is fun." <== definitely a string

That's what you need to do. Add a '\0' at the end.

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