+ 1

This Program is working on gcc, clang and tcc compilers with modes: -Wall -pedantic but here it is not working properly

#include <stdio.h> #include <stdlib.h> #include <ctype.h> int main() { char* str= (char*)malloc(sizeof(char)); str[0]= '\0'; int i=0; char get; get=getchar(); while( get!='\0' && get!='\n') { i++; if(isupper(get)){ str= (char*)realloc(str, (i+1)* sizeof(char)); str[i-1]= '_'; i++; } str= (char*)realloc(str, (i+1)* sizeof(char)); str[i-1]= tolower(get); str[i]='\0'; get=getchar(); } puts(str); return 0; }

1st Nov 2024, 8:44 PM
Chandan Das
Chandan Das - avatar
8 odpowiedzi
+ 2
Your program loops until it receives a NULL or a NEWLINE. In SoloLearn, that's breaking. To make this program work, when you input the data to run the script, add a NEWLINE at the end of your data. Type your word, press ENTER, your cursor goes to the next line. THEN submit it. It will work. To fix this, you'll need to test the condition differently. I don't know why - but in SoloLearn, after the end of the characters it starts returning -1. So you can fix your program by testing for -1. while( get!='\0' && get!='\n' && get!= -1) NOTE: How I solved this was I added a print statement below the second get=getchar(); line. printf("%c:%d\n", get, get); That prints the character being input as well as the integer value of that character.
1st Nov 2024, 10:32 PM
Jerry Hobby
Jerry Hobby - avatar
+ 3
Jerry Hobby the reason for -1 is that is the value for EOF. Remember that Sololearn's batch script saves your console input into a text file, and then redirects stdin to come from that file. So unless the user enters a null or newline as the last character it will encounter EOF. while (get!='\0' && get!='\n' && get!=EOF)
2nd Nov 2024, 1:38 AM
Brian
Brian - avatar
+ 2
Bob_Li I added the print statement mentioned in my comment. It showed -1. I was expecting a newline or null. Surprised me. Printf is the best debugging tool. lol
2nd Nov 2024, 1:23 AM
Jerry Hobby
Jerry Hobby - avatar
+ 2
Brian lol. you are correct sir. Thanks for that clarification. I love the brilliant minds around here.
2nd Nov 2024, 2:34 AM
Jerry Hobby
Jerry Hobby - avatar
+ 1
Jerry Hobby How did you find out about Sololearn returning -1? This is new to me. Just curious about the method.
2nd Nov 2024, 1:18 AM
Bob_Li
Bob_Li - avatar
+ 1
Jerry Hobby sorry I missed something that is explicitly written...😅 Great detective work. Print debugging is also my weapon of choice. Nice and simple.
2nd Nov 2024, 1:34 AM
Bob_Li
Bob_Li - avatar
+ 1
Brian yes, that input box have to come from somewhere.
2nd Nov 2024, 1:52 AM
Bob_Li
Bob_Li - avatar
0
Thank you all for helping me.
2nd Nov 2024, 4:04 AM
Chandan Das
Chandan Das - avatar