In: Computer Science
Hi i need a c++ program that can convert charactor into numbers
pseodocode
user input their name
for example john
every single charactor should have a value so it return correct result
eg:
j=2, o=1, h=7,n=2
and display these numbers
if you may need any question to ask me, i will be very happy to answer them.
Thanks!
example project close but not accurate
#include<iostream>
#include<string>
#include<exception>
#include <cstdlib>
#include<stdio.h>
#include<map>
#include <cctype>
#include<Windows.h>
#define INPUT_SIZE 8
using namespace std;
// Function to reverse a string
void reverseStr(string& str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
int main() {
const std::string alpha =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string text;
std::cin >> text;
// convert all lower case characters to upper
case
for (char& c : text) c = std::toupper(c);
// sum up the values of alpha characters ('A' == 1,
'B' == 2 etc.)
int sum = 0;
for (char& c : text) // for each character c in
text
{
// locate the character in
alpha
//
http://www.cplusplus.com/reference/string/string/find/
const auto pos = alpha.find(c);
if (pos != std::string::npos) //
if found (if the character is an alpha character)
// note:
non-alpha characters are ignored
{
const int value
= pos + 1; // +1 because position of 'A' is 0, value of 'A' is
1
sum +=
value;
cout <<
sum;
}
}
Hi,
Please find the C++ program below:
There is some unnecessary function and code logic in the program.
There is no need to reverse a string. Iterate over the name and perform a lookup in the alpha array.
Calculation of sum of indices is not needed.
C++ program:
-----------------
/******************************************************************************
C++ program.
*******************************************************************************/
#include<iostream>
#include<string>
#include<exception>
#include <cstdlib>
#include<stdio.h>
#include<map>
#include <cctype>
#define INPUT_SIZE 8
using namespace std;
int main() {
const std::string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "Please enter your the name:";
std::string text;
std::cin >> text;
// convert all lower case characters to upper case
for (char& c : text) c = std::toupper(c);
// Lookup character
for (char& c : text) // for each character c in text
{
const auto pos = alpha.find(c);
if (pos != std::string::npos) // if found (if the character is an alpha character)
// note: non-alpha characters are ignored
{
const int value = pos + 1; // +1 because position of 'A' is 0, value of 'A' is 1
// Print the character and the position
cout << c << "=" << pos << endl ;
}
}
}
Screenshot
Can you let me know the output for j=2 , o=1 , h=7 and n=2 ?
Kindly let me know if you need more help on this.
Hope this helps.