Reading of a String

Asked

Viewed 46 times

-2

If I have a string that is:

String s = "2123dog";

How can I calculate the first character 2 to transform the next 2 characters into an integer, and 4 to transform the name that is dog?

The result would be ( 12, dog )?

  • 1

    Apart from the question being unclear what the goal is and it seems to say one thing and the answer it accepts seems to do another, in what language are you asking? Neither seems C or C++, although technically it would be possible but highly unlikely.

1 answer

0


I don’t know if I understood your question correctly, but maybe it was something like this:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "2123dog";
    int n = stoi(s.substr(0, 1), NULL);
    int n2 = stoi(s.substr(1, n), NULL);
    int n3 = stoi(s.substr(1 + n, 2 + n), NULL);
    string resto = s.substr(2 + n);
    cout << n << " - " << n2 << " - " << n3 << " - " << resto;
    return 0;
}

The exit is: 2 - 12 - 3 - dog. Note that all three numbers were stored in type variables int.

See here working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.