开发者

c language : read file content as numbers and add them together

开发者 https://www.devze.com 2023-01-27 22:37 出处:网络
I have the following in a text file called: values.txt 1 4 2.5 3.76 122 10 277.543 165.4432 I am trying to read the content of this text file, and add each two pairs together and output the resul

I have the following in a text file called: values.txt

1 4 
2.5 3.76
122 10
277.543 
165.4432

I am trying to read the content of this text file, and add each two pairs together and output the result ... the output would be something like this :

1 Pair:(1, 4) = 5

2 Pair:(2.5, 3.76)= 6.26

and so on ..

I am opening the file like this

int c;
FILE myfile; 

myfile= fopen("values.txt", "r"); 
if ( m开发者_如何学Goyfile == NULL ) { 
  printf("Cannot open TEXT file\n");
  return 1; 
}

double aa,bb;
while ( (c = getc(myfile) ) != EOF ) { 
    // HERE SHOULD I DO THE OUTPUT BUT HOW?
}

Any help is really appreciated ..

Language = C


The following code does what you expect. myfile should be declared as FILE*. fopen returns a pointer to FILE structure. If the file is very large, I would recommend reading in buffers of big size (eg: 65535 etc) and parse it char by char and convert it to float values. It reduces system call overhead which takes more time than processing text to float values.

#include <stdio.h>
#include <string.h>

main(int argc, char *argv[])
{
    FILE* myfile; 

    myfile = fopen("values.txt", "r"); 
    if ( myfile == NULL ) { 
        printf("Cannot open TEXT file\n");
        return 1; 
    }

    double aa,bb;
    while (2 == fscanf(myfile, "%lf %lf", &aa, &bb)) {
        printf("%lf\n", aa+bb);
    }
    return 0;
}


For this simple task, use

double a, b;
if (fscanf(myfile, "%lf %lf", &a, &b) == 2)
        printf("%f + %f = %f\n", a, b, a+b);
.


looks like a homework problem but fscanf can read the string into a variable like:

int n;
fscanf (myfile,"%d",&n); 


You haven't shown what you need as output for the single-value lines, but this looks like a case for fgets() and sscanf(), unless you really want the two lines with a single value to be processed as a unit.

char buffer[256];
int rownum = 0;
while (fgets(buffer, sizeof(buffer), myfile) != 0)
{
    double aa, bb;
    int n = sscanf(buffer, "%lf %lf", &aa, &bb);
    if (n == 2)
        printf("%d Pair:(%g, %g) = %g\n", ++rownum, aa, bb, aa+bb);
    else if (n == 1)
        printf("%d Solo:(%g) = %g\n", ++rownum, aa, aa);
    else
    {
        printf("Failed to find any numbers in <<%s>>\n", buffer);
    }
}

If you used fscanf(myfile, "%g %g", &aa, &bb), then it would read over newlines (they count as white space) looking for numbers, so it would read one number from one line, and the second from another line. This is not usually what people are after (but when it is what you need, it is extremely useful). Error recovery with fscanf() tends to be more fraught than with fgets() and sscanf().


its in c++ sorry :( i dont know c

this is a very simple logic code for simple minde :D im a begineer too, i havent tested this prog so sorry if something goes wrong but exactly on a same principle was working my parser and it worked fine. so this is a true method. not very efficent but... do not use this program straight away, understand it's logic this will help you alot. copying that wont give you anything ...parser tutors are so rare....

int x=0; char ch = 'r'; //i'v used this equasion to avoid error on first ckeck of ch. it must be filled by something when program starts. char bigch[10]; int checknumber = 0;

float firstnumber = 0; float secondnumber = 0; float result=0;

void clearar(char frombigar[10], int xar) //this function gets bigch as a reference which means that eny changes made here, will directly affect bigch itself. ths function gets the actual length of array and puts spaces in bigch's every element to zero out numbers. we need to clear bigch of any previous numbers. down below you'l see why i needed this. 'xar' is the x from main function. its here to tell our cleaner the true length of filled bigar elements. { for (int i=0; i }

}

int main() { <------------------- //here you add file opening and reading commands while(!myfile.eof()) //while end of txt file have not been reached { ch=myfile.get(); //gets each letter into ch, and make cursor one step forward in txt file for further reading. get() does cursor forwarding automatically

 if (ch!= "  ")                   //i used space as an indicator where one number ends
                                  //so while space havent been reahced, read letters.
    { bigch[x] = ch;              //get read letter into bigch array. 
      x++;                        //icrement bigch array step

    }
 else 

 if(ch == " ")             //if space is reached that means one number has ended and
  {                        im trying to set a flag at that moment. it will be used further.
    checknumber++;         the flag is simple number. first space will set checknumber to 1
                           second space will set it to 2. thats all.
  } 

  if (checknumber == 1)                      //if our checknumber is 1, wich means that reading  
                                             of first number is done, lets make one whole float              
                                             from that bigch array.

{ firstnumber = atof(bigch); //here we get bigch, atof (array to float) command converts bigch array into one whole float number.

   clearar(bigch,x);                             //here we send bigch and its element step into function where  
                                                 bigch gets cleaned because we dont want some ghost numbers in it.
                                                 abviously clearar function cleans bigch int main function aswell, 
                                                  not only in it's teritory. its a global cleaning :)
         }
    else if (checknumber ==2)                     //here we do the same but if flag is 2 this means that two spaces
                                                  had been passed and its time to convert bigch into secondnumber.
            { secondnumber = atof(bigch);          //same method of converting array into float (it hates other
                                                   not number letters, i mean if its a number its fine. if in your text
                                                   was 'a' or 's' in that case atof will panic hehe.. )
             clearar(bigch,x);                     //same thing, we send bigch to cleaner function to kill any numbers 
                                                    it, we get one space letter ( " " ) into each element of bigch.
            }

checknumber = 0; if both two numbers had been read out and converted. we need to reset space flagger. and start counting form 0; for next pair numbers.

result = firstnumber+secondnumber; well here everything is clear. } }

0

精彩评论

暂无评论...
验证码 换一张
取 消