我有一个名为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.
`
if(inputLine.at(0) == '%')
得到满足,意味着您将在行中传递给std::stoi
的字符串
int burnRate = stoi(inputLine);
以%
开头。
整数表示形式(在修剪空格之后)必须以加号或减号或数字开头,以便stoi
能够识别它。它不能以百分号开头。因此,此字符串不包含有效的整数表示形式,并且异常告诉您。如果要转换百分号后的数字,则需要首先形成适当的子字符串(
std::string
具有substr
方法)并将其传递给std::stoi
。