|
From: Per W. <pw...@ia...> - 2004-11-22 23:12:19
|
Your program isn't reading numbers from the file. It is reading
characters.
If your file constains "123" your program will add
'1' + '2' + '3' which is
49 + 50 + 51
Also, your program is adding the EOF return value. You should test for EOF
before adding...
If you want to convert a single ascii digit to it's integer value you have
to do (c - '0').
Also, since you haven't specified if your numbers may be more than
single-digit or if they are separated by something, we can't really help
with suggestions for better methods to read from the file.
/Per W
On Mon, 22 Nov 2004, Gabriel Alejand Ya=F1ez Lemus wrote:
> Hi!!
> I made a source code in C for read numbers from a file, plus them and sho=
w
> the result on screen.This is the code.
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int main()
> {
> FILE *nombre;
> int c,a=3D0;
>
> nombre =3D fopen("Prueba.txt", "r");
>
> if (nombre =3D=3D NULL)
> {
> printf("El archivo no existe \n");
> exit (EXIT_FAILURE);
> }
> else
> {
> do
> {
> c =3D getc(nombre);
> a=3Da +c;
>
> }
> while (c !=3D EOF);
> }
> printf("%d",a);
> fclose(nombre);
>
> return EXIT_SUCCESS;
> }
>
> I don't know why this code doesn't work. The file "prueba.txt" contains
> the numbers 2 3 and 3.The program must do "2+3+3" and show on screen "8"
> but i don't know what's wrong, the program shows "151".
>
> Help me please!
>
> Anybody have a good day!
>
>
>
>
>
>
> -------------------------------------------------------
> SF email is sponsored by - The IT Product Guide
> Read honest & candid reviews on hundreds of IT Products from real users.
> Discover which products truly live up to the hype. Start reading now.
> http://productguide.itmanagersjournal.com/
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|