Click here to Skip to main content
15,920,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've tried to practice c++ and this is what I wanted

=======================================================
Input : (put some letters, in this case, I will put AAA) AAA
Output : (print each ascii code value of them in this way ) 97 + 97 + 97 = 291
=======================================================

What I have tried:

C++
#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
	char str[32] = { 0 };
	int value = 0, i;
	cout << "Input: ";
	cin >> str;

	for (i=0;i<32;i++)
	{
		value += str[i];
	}

	cout << "Output:" << value << endl;
	
    return 0;
}
Posted
Updated 9-Apr-18 1:58am
v2

You have to limit the loop to the number of characters entered. Because you are using C++, there is also no need to use a character array. Use std::string instead:
C++
std::string str;
cin >> str;
for (size_t i = 0; i < str.length(); i++)
{
    value += str[i];
}
// Or since C++11
for (char& c : str)
{
    value += c;
}
Note also that you forgot to print out each single ASCII code which can be done easily in the loop.
 
Share this answer
 
Comments
CPallini 9-Apr-18 8:45am    
5.
Casting the value to int ((int)str[i]) will give you the numerical value (not certainly ASCII, as it may depend of your local) of the char, but your way of '+=' will not create a printable line like in your example, but only the final result (sum)...
If you want to add each char's value to the output, put a cout inside the loop too...
 
Share this answer
 
You only missed the correct termination of your loop.
C++
for (i=0;i<strlen(str);i++)

A better solution would also be to use the std::string class.

I hope it helps, because you havent provided any detailed error description.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900