how can I print ascii code value in c++ in this way? - c++

I'd like to show each letter's ascii code
for example
Input: HelloWorld
Ascii Value: 72 + 101 + 108 ... = 1100
And here's my now-code
#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 << "Ascii Value:" << value << endl;
return 0;
}
I only can take the total value of ascii code such as 1100,
not every code value of each letters such as 7 + 11 + ... = 1100.
How can I fix it?

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;
}

Related

Array input of multiple digit splliting into single digits (linear search)

#include <iostream>
using namespace std;
template <class T> class Linear {
private:
T *a;
T key;
int n;
public:
Linear();
void LS();
};
template <class T> Linear<T>::Linear() {
a = new T[10];
cout << "\nEnter the no. of elements in the array";
cin >> n;
cout << "\nEnter the elements in the array";
for (int i = 0; i < n; i++) cin >> a[i];
cout << "\nEnter the key value";
cin >> key;
}
template <class T> void Linear<T>::LS() {
int flag = 0, i;
for (i = 0; i < n; i++) {
if (key == a[i]) {
flag = 1;
break;
}
}
if (flag == 1) cout << "\nElement found at" << i + 1 << "index";
else cout << "\nElement not found";
}
int main() {
Linear<char> l;
l.LS();
return 0;
}
The code is intended to read multiple digits into the array. However when I input
5 23 24 25 26 27
I expect to see
23 24 25 26 27
but I see
2 3 2 4 2
The problem ( thanks to #brc-dd for clarifying ) is that cin behaves counter intuitively with regards to char types. It only reads one character at a time rather than treating char like a number which in all other respects it is. The following code demonstrates this fact
#include <iostream>
#include <stdint.h>
#include <sstream>
using namespace std;
int main(){
std::stringstream ss("27");
int8_t v_int8;
char v_char;
int v_int;
long v_long;
short v_short;
ss >> v_int8;
std::cout << v_int8 << std::endl;
ss.seekg(0);
ss >> v_char;
std::cout << v_char << std::endl;
ss.seekg(0);
ss >> v_int;
std::cout << v_int << std::endl;
ss.seekg(0);
ss >> v_int;
std::cout << v_int << std::endl;
ss.seekg(0);
ss >> v_short;
std::cout << v_short << std::endl;
ss.seekg(0);
ss >> v_long;
std::cout << v_long << std::endl;
ss.seekg(0);
}
the output being
2
2
27
27
27
27
Note that even if you try to get clever and use int8_t it is really only an alias for char and will read character by character rather than as a number like you might assume.
Note: stringstream is like using cin except the input comes from a string instead of user input. ss.seekg(0) just puts the stream back to the beginning of the string.

Converting an Ascii Character to an Integer

Hey guys I have a program here that basically needs a key to open encrypted data but for some reason every time I run the program when converting the Ascii numbers to characters I get characters with the wrong Ascii value. For example in the code below if it tried converting the Ascii Value '50' to a char I would get 'e' instead of '2'. Any help would be much appreciated.
#include "stdafx.h"
#include "iostream"
#include "string"
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
string key = "5053525055";
int asciiValues;
char asciiChars;
for (int i = 0; i < key.length(); i += 2)
{
asciiValues = (int)(key[i] + key[i + 1]);
asciiChars = (int)(key[i] + key[i + 1]);
}
Here's the complete code for those interested.
#include "stdafx.h"
#include "iostream"
#include "string"
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
void encryption(string text)
{
char asciiChar;
int asciiValue = 0;
string key;
string encoded;
srand((unsigned)time(0));
int random_integer = rand();
cout << random_integer << endl;
//Creates the key for the string.
for (int i = 0; i < to_string(random_integer).length(); i++)
{
int asciiValue = (char)(to_string(random_integer)[i]);
key = key + to_string(asciiValue);
cout << asciiValue << endl;
}
int help = to_string(asciiValue).length();
/*Function that converts the individual characters in the input
string to AsciiValues and then puts them into the encoded data.*/
for (int i = 0; i < text.length(); i++)
{
int asciiValue = char(text[i]) + random_integer;
encoded = encoded + to_string(asciiValue) + ".";
}
cout << "Encrypted data: " << encoded << endl;
cout << "Your key for this encoded data is " << key << endl;
}
void decryption(string text, string key)
{
char asciiChars;
int asciiValues;
int number;
string qkey;
string decoded;
/*for (int i = 0; i < to_string(random_integer).length(); i++)
{
int asciiValue = (char)(to_string(random_integer)[i]);
key = key + to_string(asciiValue);
cout << asciiValue << endl;
}*/
for (int i = 0; i < key.length(); i += 2)
{
asciiValues = (int)(key[i] + key[i + 1]);
asciiChars = (int)(key[i] + key[i + 1]);
number = asciiChars - '0';
cout << number << endl;
}
cin >> qkey;
}
int main()
{
string answer;
int question = 0;
string vkey;
ask:
cout << "Would you like to:\nEncrypt Data[1]\nDecrypt Data[2]\nExit[3]" <<
endl;
cin >> question;
if (to_string(question) != "1"&&to_string(question) !=
"2"&&to_string(question) != "3")
{
goto ask;
}
else if (to_string(question) == "1")
{
while (answer.length() > 1000 || answer.length() < 1)
{
cout << "Please enter a string that has a length of 1 to 1000
characters. ";
cin >> answer;
cout << endl;
}
encryption(answer);
cin >> answer;
goto ask;
}
else if (to_string(question) == "2")
{
cout << "Please enter the string you would like decrypted. ";
cin >> answer;
cout << endl;
cout << "Now please enter the key for the string. ";
cin >> vkey;
cout << endl;
decryption(answer, vkey);
}
return 0;
}
ASCII number characters begin at 30hex (or 48dec). Therefore '0' = 30hex. So, to get an ASCII character, you must add '0' (30h).
'cout << 5 + '0'; // 53dec (35hex)

Display duplicate characters in a string

I wrote some code in C++ to display duplicate characters in a string, but if a character is repeated more than three times, the code prints the repeated character more than once.
For example if the string is aaaddbss, it should only print out ads but it prints aaads instead.
What am I doing wrong?
cout << " Please enter a string" << endl;
cin.getline(input, 100); // example input (ahmad wahidy) the output reads a a h a d instead of a h d
for (int i = 0;input[i]!='\0'; i++)
{
for (int j = i+1;input[j]!='\0'; j++)
{
if (input[i] == input[j])
{
cout << input[i] << " ";
}
}
}
cout << endl;
Instead of using your own custom methods, why not use a short and standard method?
Given an std::string input with the text, this will print the unique chars:
std::set<char> unique(input.begin(), input.end());
for (auto & c : unique)
{
std::cout << c << " ";
}
std::cout << std::endl;
You can use std::count and std::set:
#include <string>
#include <set>
#include <iostream>
using namespace std;
int main()
{
string s = "hellohowareyou";
set<char>the_set(s.begin(), s.end());
for (char i:the_set)
if (count(s.begin(), s.end(), i) > 1)
cout << i << endl;
}
Output:
e
h
l
o
If you are not allowed to use a map (and probably also not allowed to use a set), you could simply use an array of integers to count occurrences, with one entry for each possible char value. Note that a character - when taken as an ASCII value - can be directly used as an index for an array; however, to avoid negative indices, each character value should first be converted to an unsigned value.
#include <iostream>
#include <limits>
int main() {
const char* input = "aaaddbss";
int occurrences[UCHAR_MAX+1] = { 0 };
for (int i = 0;input[i] !='\0'; i++)
{
unsigned char c = input[i];
if (occurrences[c]==0) {
occurrences[c]++;
}
else if (occurrences[c]==1) {
occurrences[c]++;
cout << "duplicate: " << c << endl;
}
}cout << endl;
}

ASCII Dec to Char in C++

I want to get every characters of ASCII in normal char. If I only put char key only, it would return dec.
My request:
char alph = //ascii dec to normal char
For example: A in dec is 65
Note: I don't have the characters, but I do have the ASCII codes in dec like 65.
because I need user input like 65
In this case you can do this:
#include <iostream>
using namespace std;
int main() {
int code;
cout << "Enter a char code:" << endl;
cin >> code;
char char_from_code = code;
cout << char_from_code << endl;
return 0;
}
This will ouput:
Enter a char code:
65
A
It seems you have misunderstood the concept.
The numerical value is always there. Whether you print it as the letter or the numerical value depends on how you print.
std::cout will print chars as letters (aka chars) so you'll need to cast it to another integer type to print the value.
char c = 'a';
cout << c << endl; // Prints a
cout << (uint32_t)c << endl; // Prints 97
cout << endl;
uint32_t i=98;
cout << i << endl;
cout << (char)i << endl;
Output:
a
97
98
b
This is the method, very simple and then just need to make your own user interface to get input dec
#include <iostream>
using namespace std;
int main() {
int dec = 65;
cout << char(dec);
cin.get();
return 0;
}
Looks like you need hex/unhex converter. See at boost, or use this bicycle:
vector<unsigned char> dec2bin( const string& _hex )
{
vector<unsigned char> ret;
if( _hex.size() < 2 )
{
return ret;
}
for( size_t i = 0; i <= _hex.size() - 2; i += 2 )
{
string two = string( _hex.data() + i, 2 );
stringstream ss( two );
string ttt = ss.str();
int tmp;
ss >> /*hex >>*/ tmp;
unsigned char c = (unsigned char)tmp;
ret.insert( ret.end(), c );
}
return ret;
}
int main()
{
string a = "65";
unsigned char c = dec2bin( a )[0];
cout << (char)c << endl;
return 0;
}

How to convert ASCII value into char in C++?

How do I convert 5 random ascii values into chars?
Prompt:
Randomly generate 5 ascii values from 97 to 122 (the ascii values for all of the alphabet). As you go, determine the letter that corresponds to each ascii value and output the word formed by the 5 letters.
My Code:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main ()
{
srand (time(NULL));
int val1= rand()%122+97;
int val2= rand()%122+97;
int val3= rand()%122+97;
int val4= rand()%122+97;
int val5= rand()%122+97
cout<<val1<<" and "<<val2<<" and "<<val3<<" and "<<val4<<" and "<<val15<<". "<<
return 0;
}
To convert an int ASCII value to character you can also use:
int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
int main()
{
int v1, v2, v3, v4, v5,v6,v7;
cout << "Enter 7 vals ";
cin >> v1 >> v2 >> v3 >> v4 >> v5 >> v6 >> v7;
cout << "The phrase is "
<< char(v1)
<< char(v2) << " "
<< char(v3) << " "
<< char(v4)
<< char(v5)
<< char(v6)
<< char(v7);
system("pause>0");
}