为何在传递给stoi时,此字符串为何被视为无效参数

问题描述 投票:-1回答:1

我有一个名为getBurnRata.java的文件,提示用户输入燃烧速率,当燃烧速率小于0时,程序结束。该文件从该文件读取以获取刻录率。

string inputLine;
    if(myInputFile)
            { 
                //cout << "#opened file." <<endl ; 
                getline(cin, inputLine);
                cout << inputLine << endl ;
                do{
                        getline(cin, inputLine);
                        //getline(cin, inputLine);
                        //cout << "#input line: "<<  inputLine << endl ; 
                        //cout << "#length: " << inputLine.length() << endl ;
                        if((inputLine.empty() == false ) && (inputLine.length() > 0)){
                            // cout << "#inside notempty" <<endl ;
                            // cout << "#substr 0: " << inputLine.at(0) << endl ; 
                            // cout << "#substr 1: " << inputLine.at(1) << endl ;
                            //cout << "#substr 2: " << inputLine.at(2) << endl ;
                            if(inputLine.at(0) == '#'){
                                //cout << "#input line: "<<  inputLine << endl ;
                                cout << "# line: " << inputLine << endl ;
                            }
                            else if(inputLine.at(0) == '%'){
                                cout << "#this is %%%!!!" << endl ; 
                                cout << "#substr 0: " << inputLine.at(0) << endl ; 
                                cout << "#substr 1: " << inputLine.at(1) << endl ;
                                //cout << "#substr 2: " << inputLine.at(2) << endl ;
                                try{
                                    cout << "#inside try" << endl ; 
                                    cout <<"#inputLine: " << typeid(inputLine).name() << endl ; 

                                    int burnRate = stoi(inputLine);
                                    cout << "#burnRate: " << burnRate << endl ; 
                                }
                                catch(string error){

                                }
                            }
.......................

控制台:

inputLine: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi

我印象深刻

NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE is a string.
`
c++ c++11
1个回答
1
投票
if(inputLine.at(0) == '%')

得到满足,意味着您将在行中传递给std::stoi的字符串

int burnRate = stoi(inputLine);

%开头。

整数表示形式(在修剪空格之后)必须以加号或减号或数字开头,以便stoi能够识别它。它不能以百分号开头。因此,此字符串不包含有效的整数表示形式,并且异常告诉您。

如果要转换百分号后的数字,则需要首先形成适当的子字符串(std::string具有substr方法)并将其传递给std::stoi

© www.soinside.com 2019 - 2024. All rights reserved.