Hello, I have a couple questions about using fstream. I am curious on how I would do something like :
To begin with there is a .txt file with a set of numbers in them.
- How would I be able to read how many numbers there are in this .txt file and then take those numbers and add them?
Any help would be really great. I have been stumped with this for a couple days now and cant find the correct way to do it.
#include <iostream>
#include <fstream>
usingnamespace std;
int main() {
ifstream inputFile;
int num, amount;
inputFile.open("numbers.txt");
cout << "Reading data from the file" << endl;
while (inputFile >> num) //Displays all of the numbers in the file.
{
amount++; //Makes amount = to how many numbers there are.
cout << num << endl;
}
cout << "There are " << amount << " numbers in this file." << endl;
//This is definately not working how I want it to.
inputFile.close();
return 0;
}
std is a namespace where all standard library resides. It is better to use explicitely qualified names (std::cin) than dumping whole std namespace into global (using namespace std): name clashing and hard-to-notice bugs can follow.
but calling them one by one(see namespace in the reference section).
First of all, since you are dealing with a bunch of numbers, that means you need to have something between them right? (In the code above, inputFile>>num stops when they see /n, spaces,/t etc.(see ref.)).
Well for the last(above) post you've made, you need to specify the first value of
amount
. say int num = 0, amount = 0;
My advice is that you work on the basics first(say using a for loop instead of while) and start building up until you reach more advance topics(like vectors). Hopefully this helps. :)
That was helpful, thank you.
Alright. So basically, I am supposed to be writing a program that calculates things like the number of numbers in the file (Done with this part)
-Gets the sum of the numbers in the file. (No idea how to do this ;_;)
-ect ect..
Basically.. Im not sure how to read out the numbers and then add up those numbers or multiply them to get an average.
Also.. a bit stumped on how to make the program know the highest number on here..
Scratch all of that.. figured it out. Now I am stuck on one thing. How do I find the lowest and highest number in the .txt file and output it?