如何访问字符串中的数字并将其转换为整数?

时间:2015-07-05 12:20:51

标签: c++ arrays string c++11 procedural-programming

我在这里使用stoi函数,它给出了无效的参数错误...

这里,输入文件类似于“S13S12S11S10S1”。我想将数字保存在数组排名中,如排名[0] = 13排名[1] = 12等等......

#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";
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用“SHDC”作为分隔符来标记输入字符串。然后使用atoi将标记转换为整数。如果您的输入文件可能具有不同数量的令牌,我会使用向量来存储您的排名值。

#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;
    }
}