I'm experimenting with C and trying to get used to memory and string stuff by creating a program that takes stdin in the form of words, processes the words, spits them back out and also tries changing the word's upper and lower cases.
However, it seems like the program doesn't execute anything beyond strcpy(key, word)
. It stops right at the for loop, and doesn't even execute the print statements after the loop.
So far, I've tried both a while loop and a for loop for the case changing. I made sure key copied correctly by printf'ing it on the line above the for loop. I even commented out the for loop and saw the tolower() call two lines worked and printed out the updated key. There's just something wrong with the for loop and I don't know what.
How would I be able to fix it?
int main(void)
{
char ch;
char *word;
word = (char *)malloc(60 * sizeof(char));
int ind = 0;
int cap = 60;
while (ch = getchar()) {
if (isalnum(ch)) {
if (ind >= cap) {
word = (char *)realloc(word, (ind + 1) * sizeof(char));
cap++;
}
word[ind] = ch;
ind++;
} else {
word[ind] = '';
int size = strlen(word);
char key[size];
strcpy(key, word);
for (int i = 0; i < size; i++) {
if (i = 0) {
key[i] = toupper(key[i]);
} else {
key[i] = tolower(key[i]);
}
}
fprintf(stdout, "%s
", key);
key[0] = tolower(key[0]);
fprintf(stdout, "%s
", key);
ind = 0;
memset(word, 0, sizeof word);
putchar(ch);
putchar('
');
}
}
}
question from:
https://stackoverflow.com/questions/66059743/program-stops-at-for-loop 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…