简体   繁体   中英

How can I get the sum of integers in a text file with c++?

I apologize if this is a simple question, I'm teaching myself c++ and can't seem to find the solution I'm looking for to this one anywhere.

Say I have a text file with data organized like this:

10 - sample 1

20 - sample 2

30 - sample 3

40 - sample 4

Is there a way I can get the numbers from each line and store their sum in a variable? Or am I approaching this incorrectly? Thanks in advance!

You will need to include the <fstream> in your header file list.

Then:

1- Open your file.
2- Read it line after another.
3- Sum up the numbers.
4- Print the total.

You will need to read about files to fully understand how it works

int main()
{
        fstream MyFile;  // declare a file

        MyFile.open("c:\\temp\\Numbers.txt", ios::in); // open the file

        int sum = 0;
        string line;


        while (getline(MyFile, line))  //reading a line from the file while possible
        {
            sum = sum + stoi(line);    // convert string to number and add it to the sum
        }

        MyFile.close();   // closing the file

        cout << "sum is: " << sum;  // print the sum

    cin.get();

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM