C Excercise Input-Output Question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C Excercise Input-Output Question

Excercise: Write a program to print all input lines that are longer than 80 characters. I've written the program requested above. Actually the problem isn't printing all input lines that are longer than 80 characters. My program correctly tests it and gives output accordingly. The thing bothering me is when I press only enter and put '\n' as the only input program shuts up. I guess it is because that spesific input makes the condition in the main function -EOF- true so it shuts up. But I don't understand it because when we put \n as the input the program returns 0 as the value. To my understanding the while loop in the main function should continue until I put Ctrl-Z as input. I'd like to know how can putting enter shut the program and how can I correct it. The program should get input until the EOF. I ask for your help on these two matters. THE PROGRAM #include <stdio.h> #define MAXXX 1000 int getline (char s[], int maxlimit); main() { int line[MAXXX]; int character; while ((character = getline(line, MAXXX)) && character != EOF) { if (character >= 80) printf("%s", line ); else printf("Please put inputs including more than 80 characters \n"); } } int getline(char s[], int lim) { int i, c; for(i = 0; i < lim && (c = getchar()) && c != '\n'; ++i) s[i] = c; if ( c = '\n') { s[i] = c; ++i; } s[i] = '\0'; return i - 1; }

1st Feb 2020, 8:23 AM
mert aydın
2 Answers
+ 2
The condition in the while loop is kinda nonsense: you're storing the number of characters in a variable called character (please call it something like char_num or num_of_chars) and then you check whether this number equals EOF!? Of course a number can technically have the same value as EOF but comparing char values with numbers doesn't make any sense. Also there's a bug in the getline function: if (c = '\n') should be if (c == '\n') And please also fix the indentation, too, currently the code is really hard to read.
1st Feb 2020, 10:00 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
Thank you very much. I am a beginner so I've forgotten how hard it is to read someone's code. I've looked again the while loop and you are right. It is literally nonsense. I will correct the indentation as you suggested. Your help is much appreciated.
1st Feb 2020, 10:14 AM
mert aydın