Assuming my test.txt file is:
10111_2 10
62_10 2
391_10 2
67_2 10
11_10 2
The approach would be:
1. read file line by line into a string
2. find and replace the underscore character in each line with white-space (why white-space? see 4 below) - so now you have a modified string
3. construct a stringstream object with the modified string
4. stringstream reads characters up to white spaces into variables, so now read off the stringstream object created from the modified string into 3 integers - the number itself, the old base and the new base
5. save these integers in a vector of tuples
6. range loop (or iteratw if you wish) across the vector, running the appropriate base conversion function for each vector element. Note, I have declared, but not defined, the base conversion functions. You mention having code for converting base 2 to base 10 and you can search for the base 10 to base 2 conversion function and add in any other required header files
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include<iostream>
#include<fstream>
#include<sstream>
#include<vector>
#include<tuple>
using namespace std;
int conv10to2(int num);
int conv2to10(int num);
int main(){
ifstream File;
vector<tuple<int, int, int>> v;
int num, old_base, new_base;
File.open("F:\\test.txt");
if(File.is_open()){
string line;
while(getline(File, line)){
replace(line.begin(), line.end(), '_', ' ');
stringstream stream(line);
while(stream>>num>>old_base>>new_base){
v.emplace_back(num, old_base, new_base);
}
}
}
for (auto& itr:v){
if(get<2>(itr) == 2){
cout<<get<0>(itr)<<"base "<<get<1>(itr)<<"is "<<conv10to2(get<0>(itr))<<"base "<<get<2>(itr)<<endl;
}
else{
cout<<get<0>(itr)<<"base "<<get<1>(itr)<<"is "<<conv2to10(get<0>(itr))<<"base "<<get<2>(itr)<<endl;
}
}
}
|
Edit: upon further reading there are some suggestions that the numbers should be saved as doubles, not integers, take a look