G
G
Gagatyn2016-09-23 23:54:43
PHP
Gagatyn, 2016-09-23 23:54:43

How to calculate the sum of numbers in a file?

char buff[11]; 
float a=0;
        ofstream file;
  file.open("C:/Users/Desktop/test.txt");
  file << "0123456789";
  file.close(); //создал, открыл, записал, закрыл

  ifstream fin("C:/Users/Desktop/test.txt"); // открыл для чтения

  fin >> buff; // считали первое слово из файла
  cout << buff; // напечатали это слово

  fin.getline(buff, 11); // считали строку из файла
  fin.close(); // закрываем файл
   for (int i = 0; i < 11; i++){
    a +=  buff[i];
    cout << buff[i] << "\t" << a << endl;
  }

How to count them, how to write them into variables? "a" prints complete nonsense, large numbers. How to work with them?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Arthur, 2016-09-13
@Tchort

make a function call in the file

<?
test($_GET['a']);
?>

Y
yurygolikov, 2016-09-13
@yurygolikov

php.net/manual/en/reserved.variables.get.php

A
Alexey, 2016-09-13
@alsopub

I don’t remember that in php there was once such a way to call functions via a GET request.
Here, access to parameters like test.php?a=123 was once possible through $a, now it is better to use $_GET{'a'} for this (and even better - then check the passed value for validity).
If you want to call several different functions - call test.php?func=test¶m=123 and in your code already do if ($_GET{'func'} == 'test') { test($_GET{'param'}); } and so on like that.

M
Mercury13, 2016-09-24
@Gagatyn

So far I see this.
1. a += buff[i];You are summing character codes, not their numerical values. Correct a += buff[i] - '0';
2. These lines duplicate each other.

fin >> buff;
  fin.getline(buff, 11);

First we get 0123456789, then the file is over and in place 0 we write the null character (NUL).
3. for (int i = 0; i < 11; i++)- non-universal design. There are only 10 plus numbers in the line, so you need i < 10.
4. So the sum of numbers or the sum of digits?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question