Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations KootK on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading single Char from String in C.

Status
Not open for further replies.

mjs84

Aerospace
Aug 20, 2003
27
I am new to C and I'm having a problem with something I thought would be relatively simple.

I am trying to read a character at a time from a string, using the getchar() function, and I seem to be having alot of trouble.
Below is my code:

*---------------------------------------------------------

FILE *fp0;
char c(10+1);
int j, ch;

fopen(fp0, "outfilename","w");

for ( j=0 ; (j<10) && ((ch=getchar()) != EOF) && (ch != '/n') ; j++)
{
c[j] = (char)ch;
fprintf(fp0, &quot;c = %c/n&quot;, c[j]);
}

fclose(fp0);

*---------------------------------------------------------

This compiles okay, but hangs up when it's executed.

Any help would be greatly appreciated.

Regards,
mjs84
 
Replies continue below

Recommended for you

Oops:

I forgot to mention. The string I am trying to read is in a string variable.

char str1[10+1];

str1 = &quot;123H.456&quot;;
 
char c(10+1);

Is this kind of initialization even allowed? (parentheses as opposed to brackets)
 
Also, it's been a long time since reaing K&R, but I'm not so sure this is a good idea (will work in most cases, though)...

(ch=getchar()) != EOF) && (ch != '/n')

Can't remember if order those pieces are computed in are guaranteed to be left to right, and if not, (ch != '/n') may not do what you think it should do.
 
oops again.
I had initialized it
char c[10+1];

I did get this to work by writing my string into a temporary file and using the getc() function to read each character of the file.

This seems to work okay.

If there are any better ideas, I would sure like to hear them.

Regards,
mjs84
 
Hi-

I think that the problem is the castings of the variables.
ch is cast as int. In your for statement by doing
comparisons as characters, the program seems to work
correctly. I've modified you program (I hope that the
formatting doesn't get screwed up......

Hint: When in doubt, throw in a printf statement

#include <stdio.h>
main(){


FILE *fp0;
char c[10+1];
int j, ch;

fp0 = fopen(&quot;outfilename&quot;,&quot;w&quot;);

//for ( j=0 ; (j<10) && ((ch=getchar()) != EOF) && (ch !='\n') ; j++)
for ( j=0 ; (j<10) && ((char)(ch=getchar()) != EOF) && ((char)ch !='\n') ; j++)
{
c[j] = (char)ch;
// printf( &quot;c = %c\n&quot;, c[j]);
fprintf(fp0, &quot;c = %c\n&quot;, c[j]);
}


fclose(fp0);

}
 
richs

Thanks for the help. I'll try it and let you know if that does it.

Thanks to all who give this valuable advice.

mjs84
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor