繁体   English   中英

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

[英]How to access numbers in string and convert it to integer?

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

在这里,输入文件类似于“ S13S12S11S10S1”。 我想将数字保存在数组中,例如rank [0] = 13 rank [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";
    }

}

您可以使用“ 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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM