简体   繁体   中英

Converting letters to numbers in C++

PROBLEM SOLVED: thanks everyone!

I am almost entirely new to C++ so I apologise in advance if the question seems trivial.

I am trying to convert a string of letters to a set of 2 digit numbers where a = 10, b = 11, ..., Y = 34, Z = 35 so that (for example) "abc def" goes to "101112131415". How would I go about doing this? Any help would really be appreciated. Also, I don't mind whether capitalization results in the same number or a different number. Thank you very much in advance. I probably won't need it for a few days but if anyone is feeling particularly nice how would I go about reversing this process? ie "101112131415" --> "abcdef" Thanks.

EDIT: This isn't homework, I'm entirely self taught. I have completed this project before in a different language and decided to try C++ to compare the differences and try to learn C++ in the process:)

EDIT: I have roughly what I want, I just need a little bit of help converting this so that it applies to strings, thanks guys.

#include <iostream>
#include <sstream>
#include <string>

int returnVal (char x)
{
    return (int) x - 87;
}

int main()
{
    char x = 'g';
    std::cout << returnVal(x);
}

A portable method is to use a table lookup:

const unsigned int letter_to_value[] = 
{10, 11, 12, /*...*/, 35};

// ...

letter = toupper(letter);
const unsigned int index = letter - 'A';
value = letter_to_value[index];
cout << index;

Each character has it's ASCII values. Try converting your characters into ASCII and then manipulate the difference.

Example:

int x = 'a';
cout << x;

will print 97; and

int x = 'a';
cout << x - 87;

will print 10.

Hence, you could write a function like this:

int returnVal(char x)
{
    return (int)x - 87;
}

to get the required output.

And your main program could look like:

int main()
{
    string s = "abcdef"
    for (unsigned int i = 0; i < s.length(); i++)
    {
        cout << returnVal(s[i]);
    }
    return 0;
}

This is a simple way to do it, if not messy.

map<char, int> vals; // maps a character to an integer

int g = 1; // if a needs to be 10 then set g = 10

string alphabet = "abcdefghijklmnopqrstuvwxyz";

for(char c : alphabet) { // kooky krazy for loop
    vals[c] = g;
    g++;
}

What Daniel said, try it out for yourself.

As a starting point though, casting:

int i = (int)string[0] + offset;

will get you your number from character, and: stringstream will be useful too.

How would I go about doing this?

By trying to do something first, and looking for help only if you feel you cannot advance.

That being said, the most obvious solution that comes to mind is based on the fact that characters (ie 'a' , 'G' ) are really numbers. Suppose you have the following:

char c = 'a';

You can get the number associated with c by doing:

int n = static_cast<int>(c);

Then, add some offset to 'n':

n += 10;

...and cast it back to a char :

c = static_cast<char>(n);

Note: The above assumes that characters are consecutive, ie the number corresponding to 'a' is equal to the one corresponding to 'z' minus the amount of letters between the two. This usually holds, though.

This can work

int Number = 123; // number to be converted to a string

string Result; // string which will contain the result

ostringstream convert; // stream used for the conversion

convert << Number; // insert the textual representation of 'Number' in the characters in the stream

Result = convert.str(); // set 'Result' to the contents of the stream

you should add this headers #include <sstream> #include <string>

Many answers will tell you that characters are encoded in ASCII and that you can convert a letter to an index by subtracting 'a' .

This is not proper C++. It is acceptable when your program requirements include a specification that ASCII is in use. However, the C++ standard alone does not require this. There are C++ implementations with other character sets.

In the absence of knowledge that ASCII is in use, you can use translation tables:

#include <limits.h>

// Define a table to translate from characters to desired codes:
static unsigned int Translate[UCHAR_MAX] =
{
    ['a'] = 10,
    ['b'] = 11,
    …
};

Then you may translate characters to numbers by looking them up in the table:

unsigned char x = something;

int result = Translate[x];

Once you have the translation, you could print it as two digits using printf("%02d", result); .

Translating in the other direction requires reading two characters, converting them to a number (interpreting them as decimal), and performing a similar translation. You might have a different translation table set up for this reverse translation.

Just do this !

(s[i] - 'A' + 1)

Basically we are converting a char to number by subtracting it by A and then adding 1 to match the number and letters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM