Click here to Skip to main content
15,912,069 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
/* The below program receives strings from keyboard and writes them to file */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main( )
{
FILE *p ;
char string[80] ;
p = fopen ( "check.txt", "w" ) ;
if ( p == NULL )
{
puts ( "Unable to open file" ) ;
exit(1) ;
}
printf ( "\nEnter text :\n" ) ;
while ( strlen ( gets ( string ) ) > 0 )
{
fputs ( string, p ) ;
fputs ( "\n", p ) ;
}
fclose ( p ) ;
getch();
}


In the above program I am not able to understand the working of the while condition >> while ( strlen ( gets ( string ) ) > 0 ) <<


Please help me understand it.Please let me know if more clarity in the question is needed.
Posted
Updated 4-Dec-14 16:18pm
v4
Comments
barneyman 4-Dec-14 21:17pm    
like all bracketed statements, work from the inside out

gets takes string as a param, and happens to return the same string

strlen is then returning the length of that returned string

and while that returned length is >0 the loop continues

Just google the gets() function in c. Here is a link, http://www.tutorialspoint.com/c_standard_library/c_function_gets.htm[^]

In fact, the comment at the top of the code and the printf statement right before the while loop explain exactly what is happening.
 
Share this answer
 
The while loop can be read as the following :

C#
int mLen = 0;
char* strInput = gets ( string ); // console blocks here waiting for input
mLen = strlen(strInput);

while ( mLen > 0 )
{
   fputs ( string, p ) ;
   fputs ( "\n", p ) ;
   strInput = gets ( string ); // console blocks here waiting for input
   mLen = strlen(strInput);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900