I'm having a hard time converting the ASCII counterpart of each char in string,
my objective is to convert the average of each word
for example:
if the user input "love" the code will return 54,
the thing is this code is inside a loop and if the user input for example;
Word no.1: "love"
Word no.2: "love"
the code should return;
54
54
but my code returns 108
i guess the problem is in this part sum = static_cast<int>(compute - 64);
but I don't know the right approach for my problem
for(int x = 1; x <= numofinput; x ){
cout << "Word no. " << x << ": ";
getline(cin,words);
for(auto compute : words){
if(isalpha(compute)){
compute = toupper(compute);
sum = static_cast<int>(compute - 64);
}
}
}
CodePudding user response:
You need to set sum = 0;
for each word you do calculations on.
There are also a number of other small issues that I've commented on in this example:
#include <cctype>
#include <iostream>
#include <string>
int main() {
int numofinput = 2;
for(int x = 1; x <= numofinput; x ) {
std::cout << "Word no. " << x << ": ";
if(std::string word; std::cin >> word) { // read one word
int sum = 0; // only count the sum for this word
// auto& if you'd like to show it in uppercase later:
for(auto& compute : word) {
// use unsigned char's with the cctype functions:
auto ucompute = static_cast<unsigned char>(compute);
if(std::isalpha(ucompute)) {
compute = static_cast<char>(std::toupper(ucompute));
sum = compute - ('A' - 1); // 'A' - 1 instead of 64
}
}
std::cout << "stats for " << word << '\n'
<< "sum: " << sum << '\n'
<< "avg: " << static_cast<unsigned>(sum) / word.size() << '\n';
}
}
}