Search code examples
c++arraysstringc++11procedural-programming

How to access numbers in string and convert it to integer?


I am using stoi function here and it is giving invalid argument error...

Here, the input file is something like "S13S12S11S10S1". I want to save the numbers in an array rank like rank[0]=13 rank[1]=12 and so on...

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
 ifstream fin("input.txt");
 string input;
 fin>>input;

 int count=0;
 int val;
 int rank[4];
 for(int i=0 ; i < input.size(); i++)
 {

    string s1,s2;
    s1=input[i];
    s2=input[i+1];

    if(s1[0]!='S' && s1[0]!='H' &&s1[0]!='D' && s1[0]!='C')
    {
        int a=stoi(s1);
        rank[count]=a;

        if(s2[0]!='S' && s2[0]!='H' &&s2[0]!='D' &&s2[0]!='C')
        {
            int temp;
            int b=stoi(s2);
            rank[count]=10+b;
            count++;
            i++;
        }
        else{
            count++;
        }       
    }


}   

for (int count=0; count<=4 ; count++)
    {
    cout<<rank[count];
    cout<<"\n";
    }

}

Solution

  • You can tokenize the input string, using 'SHDC' for delimiters. And then use atoi to convert the tokens to integers. I would use a vector to store your rank values, if your input file(s) could have a varying number of tokens.

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <vector>
    using namespace std;
    
    int main()
    {
        ifstream fin("input.txt");
        string input;
        fin >> input;
    
        const char *delimiters = "SHDC";
        char *next_token = NULL;
        char *token = strtok_s(const_cast<char*>(input.c_str()), delimiters, &next_token);
    
        vector<int> values;
    
        while (token != NULL) {
            values.push_back(atoi(token));
            token = strtok_s(NULL, delimiters, &next_token);
        }
    
        for (int i = 0; i < values.size(); ++i) {
            cout << values[i] << endl;
        }
    }