Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Dec 2011
    Posts
    67
    Thanks
    20
    Thanked 1 Time in 1 Post

    Question C++ Letters to Number

    I have this so far:
    Code:
    cin>>letter;
    if(letter=="a") number=1;
    if(letter=="b") number=2;
    ....
    if(letter=="z") number=26;
    any possible way to shorten this?

  • #2
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    Make letter into a char (or just do *letter).
    Go here: http://www.asciitable.com/
    Subtract the ascii # with the input number. No conditionals really needed.

  • Users who have thanked Apothem for this post:

    UltimateCoder (01-22-2012)

  • #3
    New Coder
    Join Date
    Dec 2011
    Posts
    67
    Thanks
    20
    Thanked 1 Time in 1 Post
    Thanks I doubt you can do this but in C++ does a+1=b ?

  • #4
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    Yes. You can also do that in C++. But do note it has to be a char, not a string/char*.

  • Users who have thanked Apothem for this post:

    UltimateCoder (01-22-2012)

  • #5
    New Coder
    Join Date
    Dec 2011
    Posts
    67
    Thanks
    20
    Thanked 1 Time in 1 Post
    This solves the problem thanks


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •