Re: can't read file?



nick <i141802596@xxxxxxxxx> writes:
> the following code is used to read a file called "input.txt"
> # include <stdio.h>
> int main(int argc,char *argv[]){
> FILE *fp;
> int ch;
> fp=fopen("input.txt","r");
> ch=fscanf(fp,"%d",&ch);
> printf("%d\n",ch);
>
> fclose(fp);
> return 0;
> }
>
> the contains in "input.txt"
> 3
> 3 14
> 2 8
> -1 0
>
>
> when i run the program the output is:
> 1
>
> what's going on?
> why the output is not 3?

fscanf() returns the number of items scanned, which in this case will
be 1 if it succeeds. You're passing &ch as an argument to fcanf()
*and* you're assigning the result to ch. Don't do that.

(I'm not certain whether it invokes undefined behavior, but it's
certainly not what you want to do .)

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: @_ aliasing
    ... by assigning them to lexically scoped vars unless you're sure ... you want to change the aliased variables. ... Prev by Date: ...
    (comp.lang.perl.misc)
  • Re: Getting value from asp:label into javascript input value
    ... In regular asp the syntax for assigning an asp global variable to a ... javascript var is: ... Prev by Date: ...
    (comp.lang.javascript)
  • Re: Trouble inserting record...?
    ... > I am sure that I am missin' something, ... At the point that you are assigning those values, you don't have a record open to insert them into. ... It's about priorities." ... Prev by Date: ...
    (comp.databases.paradox)
  • Object instantiation and garbage collection
    ... What's more efficient from a performance/garbage collection point of ... view - assigning an object to a variable or not? ... Prev by Date: ...
    (comp.lang.java.programmer)
  • Re: How to initialize and array in a structure?
    ... fflush() on an input stream invokes undefined behavior. ... Prev by Date: ...
    (comp.lang.c)

Loading