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!
asked May 13, 2017 at 3:30 Blake Greene Blake Greene 13 1 1 silver badge 4 4 bronze badges Break the task into smaller ones. Each of them is already answered. Commented May 13, 2017 at 4:43 @Blake Greene: You can check my answer below, and please have a look at this page. Commented May 13, 2017 at 5:10You will need to include the in your header file list.
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