+ 4
Read a String Of Unknown Length : C
I Want To read a string of Unknown Length, Please tell me why when I want to run this Code using SoloLearn C Compiler, the result is "No Output" !!!!!? #include <stdio.h> #include <stdlib.h> #include <string.h> void GetStr (char* , char**); int main() { char *Str =NULL; GetStr("Enter the String:- ",&Str); printf("The String is:- %s \nAnd It's length:- %lu\n",Str,(strlen(Str))); free(Str); } void GetStr(char *str,char **P_strp) { printf("%s",str); for(int i=0 ; 1 ; i++) { if(i) *P_strp = (char*)realloc((*P_strp) , i+1); else *P_strp = (char*)malloc(i+1); (*P_strp)[i]=getchar(); if((*P_strp)[i] == '\n') { (*P_strp)[i]= '\0'; break; } } }
16 Respuestas
+ 6
H. Ahmadian the fix is simple.
Along with newline character, use EOF(End Of File) as delimiter. Like this, loop will break if the user enters a newline character or there is no more to read from input.
Here is the fix 👇
https://code.sololearn.com/c5AkrEzE6i02/?ref=app
+ 4
H. Ahmadian when giving an input to your program, you must be giving it a single line string let say "hello" without a line break at the end which will lead to infinite loop as there is not '\n' at the end of the input string.
Instead if you give 2 line input like this :-
"Hello
"
// notice the double quote denoting the end of string here is in next line
Then your program will work as now there is a newline character at the end of string "hello" which is making your loop break and generating desired output.
+ 4
Arsenic Yes! You're right!!
It needs 2 line Break, and only the characters of first line will be intercepted by program.
Do you have any idea to make it work !?
Thanks anyhow for your assistance as you did Always 🙏
+ 4
Arsenic
Thank You so much, you're Awesome as Always 🙏
+ 3
Your loop on line 22 ( in function GetStr() ) will break only when it will encounter an newline character at the end of the input string.
Which you might not be provided when giving input leading to an infinite loop.
Your code works as intended when an extra newline character is added at the end of the input.
+ 3
Martin Taylor
Your Code is Great 👍
But the main problem still exists! The result of Run on the SoloLearn C Compiler is "No output"
+ 2
H. Ahmadian you're most welcome 🙂
+ 2
Martin Taylor No doubt your code written in Professional way and to be honest I really impressed.
Yeah, I tested your code without any input and the result is what you mentioned. But when I want to test using one or multiple line string Input the result is still "No output".
Maybe my keyboard has a problem, I'm using Xiaomi Redmi 5 Plus, Android v8.1, Gboard English US.
I don't know what is the problem, but I'm sure that your Code is Completely correct.
🙏
+ 2
Martin Taylor
👏👏👏👏👏👏👏
0
SoloLearn C Compiler
https://code.sololearn.com/c65rGtbx1dTv/?ref=app
0
Arsenic I didn't get it! The loop must end somehow!! How I can change it in a way you say!?