0
Can anyone help me understand this program please?
#include <stdio.h> int string_length(char str[]) { int i, length = 0; for(i = 0; str[i] != '\0'; i++) { length++; } return length; } int main() { char country[100]; int length; while(1 == scanf("%s", country)) { length = string_length(country); printf("length: %d\n", length); } return 0; } //The problem is with this line: (1==scanf("%s",country)) Why is it 1? It can be 0 also?
6 Respuestas
+ 2
scanf() return the number of successful inputs scanned(read).
scanf("%s", country) has one format specifier used for string input. If the input is successful (user enters anything) then it will return 1 in this case since there is only single input to be read. In case if scanf() fails to read input or user don't enter anything, then it will return 0.
So in your condition,
(1 == scanf("%s", country))
Loop will keep iterating as long as user keep entering something.
When nothing is entered or scanf() fails to scan input, then it will return 0 and loop will be terminated.
+ 1
so it means if input comes value=1 and if value = 1 make stuff's but i thing "1 ==" is useless because when value = 1 makes stuff's in while loop so its look like (1 ==(1 == ......) lol
+ 1
Thanks a lot nAutAxH AhmAd 😊😇
0
wait for input ,if input correct take string length
0
wait for input ,if input correct take string length
0
I understand that. But I am not understanding the condition. 😣 How will i understand that, input is correct?