0

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

Casper
  • 4,435
  • 10
  • 41
  • 72

4 Answers4

3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2
#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

idanshmu
  • 5,061
  • 6
  • 46
  • 92
  • Nice. However, the digit is a string. How to convert it to a int form? I am not familiar with function atos(). – Casper Oct 21 '13 at 07:00
  • @CasperLi Each character in the string is an integer actually. They have values like 49, 50, etc. in the ASCII alphabet. So this answer extracts each character from the string, converts the ASCII code to a value between `0` and `9` (if the characters are indeed digits) and store them in `int` variables `a`, `b` etc. – Some programmer dude Oct 21 '13 at 07:12
  • However, when I do this, I get 49, 50, 51, 52 instead of 1, 2, 3, 4 in a, b, c, d. So how can I deal with this problem? – Casper Oct 26 '13 at 13:52
2
std::string n ("12345");
int a, b, c, d, e;

a = str.at(0);
...
Mr. Smith
  • 559
  • 1
  • 5
  • 17
1

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

Community
  • 1
  • 1
AlvaroAV
  • 10,335
  • 12
  • 60
  • 91