This program reads strings of numbers from a txt file, converts them to integers, stores them in a vector, and then tries to output them in an organized fashion like so....
If txt file says:
7 5 5 7 3 117 5
The program outputs:
3
5 3
7 2
117
so if the number occurs more than once it outputs how many times that happens. Here is the code so far.
Solved: Final code:
#include "std_lib_facilities.h"
void print_numbers(const vector<int>& num)
{
int counter = 1;
for(int i = 0; i < num.size(); ++i)
{
if(i<num.size()-1 && num[i] == num[i+1]) ++counter;
else if(i<num.size()-1 && num[i]!=num[i+1])
{
if(counter > 1)
{
cout << num[i] << '\t' << counter << endl;
counter = 1;
}
else cout << num[i] << endl;
}
else if(i == num.size()-1)
{
if(counter >1) cout << num[i] << '\t' << counter << endl;
else cout << num[i] << endl;
}
}
}
int str_to_int(string& s)
{
stringstream ss(s);
int num;
ss >> num;
return num;
}
int main()
{
cout << "Enter file name.\n";
string file;
cin >> file;
ifstream f(file.c_str(), ios::in);
string num;
vector<int> numbers;
while(f>>num)
{
int number = str_to_int(num);
numbers.push_back(number);
}
sort(numbers.begin(), numbers.end());
print_numbers(numbers);
keep_window_open();
}