Reputation: 13
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!
Upvotes: 1
Views: 8371
Reputation: 1771
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;
}
Upvotes: 2