Joshua LI
Joshua LI

Reputation: 4723

How to get a digit from a string?

For example, there is a string n containing "1234".

string n = "1234"

Now, there are int a, b, c, d for storing 1, 2, 3, 4 separately.

a is 1
b is 2
c is 3
d is 4

How to get those digits from string "12345" by using a standard function?


Previously, I use the following way.

int getDigit(string fourDigitString,int order)
{
    std::string myString = fourDigitString;
    int fourDigitInt = atoi( myString.c_str() ); // convert string fourDigitString to int fourDigitInt
    int result;
    int divisor = 4 - order;
    result = fourDigitInt / powerOfTen(divisor);
    result = result % 10;
    return result;
}

Thank you for your attention

Upvotes: 0

Views: 841

Answers (4)

idanshmu
idanshmu

Reputation: 5251

#include <iostream>
using namespace std;

int main() {

    string n = "12345";

    int a = n[0] - '0';
    int b = n[1] - '0';
    int c = n[2] - '0';
    int d = n[3] - '0';
    int e = n[4] - '0';

    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cout << d << endl;
    cout << e << endl;
}

output:
1
2
3
4
5

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409136

To elaborate on my comment and the answer by ShaltielQuack, so you know why you just subtract the character '0' from the digit, you might want to look at an ASCII table.

There you will see that the ASCII code for the character '0' is decimal 48. If you then see the ASCII code for e.g. '1' it's one more, 49. So if you do '1' - '0' it's the same as doing 49 - 48 which result in the decimal value 1.

Upvotes: 3

Mr. Smith
Mr. Smith

Reputation: 639

std::string n ("12345");
int a, b, c, d, e;

a = str.at(0);
...

Upvotes: 2

AlvaroAV
AlvaroAV

Reputation: 10553

You can try the following code:

#include <string>
#include <sstream>

int main() {
    std::string s = "100 123 42";
    std::istringstream is( s );
    int n;
    while( is >> n ) {
         // do something with n
    }
}

from this question: splitting int from a string

Upvotes: 1

Related Questions