I'm trying to make a program that converts decimal numbers to a certain base and then finding how many times the largest number (1-8) in that base appears.
string conv(int decimal, int base);
vector<int>base10nums;
vector<string>differentbase;
int main(){
int num,base,start;
cin>>num>>base>>start;
for(int i=0;i<num;++i){
base10nums.push_back(start+i);
}
for(int i=0;i<num;++i){
string x=conv(base10nums[i],base);
differentbase.push_back(x);
}
int u=0;
int largestdigit=base-1;
for(int i=0;i<num;++i){
string l=differentbase[i]; //error here
for(int j=0;j<differentbase[i].length();++i){
if(largestdigit==8){
if(l[j]=='8'){ //error here
u++;
}
}
if(largestdigit==7){
if(l[j]=='7'){
u++;
}
}
if(largestdigit==6){
if(l[j]=='6'){
u++;
}
}
if(largestdigit==5){
if(l[j]=='5'){
u++;
}
}
if(largestdigit==4){
if(l[j]=='4'){
u++;
}
}
if(largestdigit==3){
if(l[j]=='3'){
u++;
}
}
if(largestdigit==2){
if(l[j]=='2'){
u++;
}
}
if(largestdigit==1){
if(l[j]=='1'){
u++;
}
}
}
}
std::cout<<u;
}
std::string conv(int decimal, int base){
if(decimal == 0) return "0";
char NUMS[] = "0123456789ABCDEF";
std::string result = "";
do{
result.push_back(NUMS[decimal%base]);
decimal /= base;
}while(decimal != 0);
return std::string(result.rbegin(), result.rend());
}
In the part with a bunch of if
s, I'm trying to compare each digit in each number in base base
to the largest digit. I can run the program, but I don't get the right value and when I hover over the l[j]
part in VSCode, I get the error:
"inline char &std::string::operator[](std::size_t __pos)
+1 overloadSubscript access to the data contained in the %string.
Parameters:
__pos – The index of the character to access.Returns:
Read/write reference to the character. This operator allows for easy, array-style, data access. Note that data access with this operator is unchecked and out_of_range lookups are not defined. (For checked lookups seeat()
.)"
Any help is appreciated!