All code must be in C++ using G++ compiler Write a program that reads all the nu
ID: 3810449 • Letter: A
Question
All code must be in C++ using G++ compiler
Write a program that reads all the numbers from an input file called "numbers.txt" and stores them in a vector. After reading in all the values, print the size of the vector. Next, use a while loop to empty the vector, printing each value before it is removed. Constraints: You must use the .size(), .at(), .push_back() and .empty() member functions. Example://don't print this "Numbers, txt" contains: 67 34 94 Output: There are 3 numbers in the file: 94 34 67Explanation / Answer
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main() {
vector<int> v;
ifstream inputFile;
inputFile.open("numbers.txt");
int number;
if (inputFile.is_open()) {
while (!inputFile.eof()) {
inputFile >> number;
v.push_back(number);
}
}
cout<<"There are "<<v.size()<<" in the file."<<endl;
for(int i=0; i<v.size(); i++){
cout<<v.at(i)<<" ";
}
cout<<endl;
inputFile.close();
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
There are 3 in the file.
67 34 94
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.