Hi, i was looking for a sample code for reading in a word by looping scanf and so on, and be able to print it out again. i'm actually trying to write a program to count words, syllabals and lines in text, but i'm just starting slow. thx.
Hi, i was looking for a sample code for reading in a word by looping scanf and so on, and be able to print it out again. i'm actually trying to write a program to count words, syllabals and lines in text, but i'm just starting slow. thx.
Last edited by BNG; 02-25-2005 at 07:22 PM.
this bit of code reads a text and stores in a string and prints back again
Code:#include<stdio.h> int main() { char str[30],c; int i=0; do { c=getchar(); if(i<=30) str[i++]=c; } while(c!=EOF); //in windows its ctl+Z == EOF str[i]='\0'; printf("%s",str); getchar(); }
I have noticed before that you assign the return value of getchar() to a type char variable. You should not do this. getchar() returns an int.Originally Posted by ssharish
~/
you are right kermit . sorry about that code
The reason you should use an int here is because you're testing for EOF. If you weren't, the assignment would be perfectly fine. However, EOF isn't a value that will fit in a char, so if it occurs and you're assigning it to a char, it will be changed to a different value so that it can fit. This in effect breaks your code, preventing it to work properly.
If however, you don't need to check for EOF, the assignment would be fine. However, since you are in fact testing it for EOF, the assignment is incorrect. Just to clarify the reason it's wrong in this case.
Quzah.
Hope is the first step on the road to disappointment.