0

I am new to C++,this problems seems to be basic. I am using char in the indices of array, everything seems to be correct, I don't understand why I am not able to fetch the value from the array, please help me!. even after typecasting char is not converting to int. The code runs fine if I use menu[n-'0'].

#include<iostream>
using namespace std;
int main(){
    char n;
    int price,q;
    float menu[]={10,20,30};
    float sum=0;
    cin>>n;
    while(n!='n' and n!='N'){
        price=menu[(int)(n)];
        cout<<price<<endl;
        cin>>n;
    }
    cout<<sum;

    return 0;
}
TruthSeeker
  • 1,539
  • 11
  • 24
Akishere
  • 37
  • 5
  • `(int)(n)` will give the ascii value of `n` which will be out of bounds for your `menu` array. This is already discussed here : [Convert char to int in C and C++](https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c) – brc-dd Oct 28 '20 at 06:47
  • Does this answer your question? [Convert char to int in C and C++](https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c) – Lukas-T Oct 28 '20 at 06:49

2 Answers2

2

So let's say that at the line cin >> n you type in "1" at the console. Then n holds the value '1', i.e. 49. If you cast this to an integer, it gives you the integer 49.

If you subtract '0', i.e. 48, from this, then it gives you a result of 1.

Also, even after subtracting '0', you should validate the input, because if the user types, say, "8" or "hello" or "!" then you're going to be trying to access memory outside your array.

Daniel McLaury
  • 4,047
  • 1
  • 15
  • 37
2

It's better to get an integer from the console instead of char at a time, and input a negative value to end the loop.

This will work if you have more than 10 prices which requires you input two characters at a time :-)

int main(){
    int n;
    int price,q;
    float menu[]={10,20,30};
    float sum=0;
    cin>>n;
    cout >> "Usage: input a price index, or -1 to terminate." << endl;
    while(n > 0){
        if (n >= sizeof(menu)/sizeof(float)) {
          cout << "Index out of range, try again!" << endl;
          continue;  // out of range
        }
        price=menu[n];
        cout<<price<<endl;
        cin>>n;
    }
    cout<<sum;

    return 0;
}
Tiger Yu
  • 744
  • 3
  • 5
  • could you please add explanation and highlight the errors? – TruthSeeker Oct 28 '20 at 06:55
  • Code-only answers are discouraged, as they tend to promote cargo cult programming which is bad. What changes did you make? Why did you make those changes? Why is it "better"? As for the code you show, how does it handle things like non-integer input? Why do you print the input prompt *after* asking for input? And how do you get out of the infinite loop when `n` is out of range? – Some programmer dude Oct 28 '20 at 06:57
  • added my explanation ;-) – Tiger Yu Oct 28 '20 at 07:01