You should use a string for your input (it’s c++, not c). Your for loop sums 32 characters, even if the user inputs a shorter string (the programm will read random values from memory). For conversion from int
to char
you can use stringstream
. This results in
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string input;
std::stringstream sstr;
int value = 0;
std::cout << "Input: ";
std::cin >> input;
for (int i = 0; i < input.size(); i++) {
sstr << int(input[i]) << " + ";
value += input[i];
}
std::string str(sstr.str());
std::cout << "Ascii Value:" << str.substr(0, str.size() - 3) << " = " << value << std::endl;
return 0;
}
2
solved how can I print ascii code value in c++ in this way?