【问题标题】:How to access numbers in string and convert it to integer?如何访问字符串中的数字并将其转换为整数?
【发布时间】:2015-09-22 16:20:21
【问题描述】:

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

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

}

【问题讨论】:

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


    【解决方案1】:

    您可以对输入字符串进行标记,使用“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;
        }
    }
    

    【讨论】:

    • s1 是一个字符串。传递给stoi 的字符在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多