Home > OS >  Is it possible to add multiple integers by user input?
Is it possible to add multiple integers by user input?

Time:12-10

Very new to "backend" and trying out this reddit challenge that I saw at r/dailyprogrammer

Challenge: Assign every lowercase letter a value, from 1 for a to 26 for z. Given a string of lowercase letters, find the sum of the values of the letters in the string.

I specifically want to do it like this but is it possible? How can a user input a word that would then add the int I've listed here so that the total sum of the word would show.

int main()
{
    int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
        a=1;
        b=2;
        c=3;
        d=4;
        e=5;
        f=6;
        g=7;
        h=8;
        i=9;
        j=10;
        k=11;
        l=12;
        m=13;
        n=14;
        o=15;
        p=16;
        q=17;
        r=18;
        s=19;
        t=20;
        u=21;
        v=22;
        w=23;
        x=24;
        y=25;
        z=26;

CodePudding user response:

This is pretty much one function call in C

std::string example = "example";
std::cout << std::accumulate(example.begin(), example.end(), 0, 
  [](int sum, char c) { return sum   (c - 'a'   1); }
  );

std::accumulate adds things in a collection. Usually, it just uses ' ' but in this case I use a custom adder [](int sum, char c) { return sum (c - 'a' 1); }. This adds not the ASCII value of c, but (c - 'a' 1). If c=='a', then c-'a'==0 and (c - 'a' 1)==1

CodePudding user response:

ok , so , this is my code and it's working ... explanation -- > we know storing a charachter in a int variable will store the ASCII value , the ASCII value of a is 97 , b is 98 so on .... subtracting 96 from each letter's ascii value will give the number you want --> if you are still confused about the ascii table then go look it up at the google you'll understand

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str ;
    cin >> str;
    int value = 0;
    for(int i=0 ; i<str.length() ; i  ){
        int v = str[i] - 96;
        value  = v;
    }
    cout << value;
    return 0;
}

CodePudding user response:

make use of the std::map<char,int>

int main(void)
{
   std::map<std::string,int> list;
   char letter = 'a';
   int val = 1;
   while(val <= 26)
   {
      list.insert(std::make_pair(letter,val));
      letter  ;
      val  ;
   }
}

CodePudding user response:

You're confusing the concept of strings and characters with a variable's name.

// a is the variable name, this is information for the programmer
int a = 1;

// 'a' here is the actual letter a, things can actually be done with this in the program
char theLetterA = 'a';

Combine this concept with std::cin so that you can read data from the user and you are on your way to figuring this out.

See:

  •  Tags:  
  • c
  • Related