Day 16: Exceptions - String to Integer
题目:
题目说明:
C++:
#include <stdlib.h>
#include <stdio.h>
#include <map>
#include <string>
#include <math.h>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
string S;
cin >> S;
try
{
int tmp = 0;
tmp = stoi(S);
cout << tmp << endl;
}
catch (exception& e)
{
cout << "Bad string";
}
system("pause");
return 0;
}
python:
import sys
S = input().strip()
try:
int_S = int(S)
print(int_S)
except ValueError:
print('Bad String')
总结:
C++:
1、stoi函数使用
将字符串转为int数字:
s1="123";
stoi(s1);
注意,stoi(),会检测int的范围,如果转化后,结果超出int范围,就报错,提示超出int范围。
详细信息,请参考:https://blog.****.net/zhuiqiuzhuoyue583/article/details/88786087
2、try catch基本用法
try
{
int tmp = 0;
tmp = stoi(S);
cout << tmp << endl;
}
catch (exception& e)
{
cout << "Bad string";
}
python:
异常:
1.以下为简单的try....except...else的语法:
try:
<语句> #运行别的代码
except <名字>:
<语句> #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句> #如果引发了'name'异常,获得附加的数据
else:
<语句> #如果没有异常发生
例子:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print "Error: 没有找到文件或读取文件失败"
else:
print "内容写入文件成功"
fh.close()
2.使用except而不带任何异常类型
try:
正常的操作
......................
except:
发生异常,执行这块代码
......................
else:
如果没有异常执行这块代码
3.try-finally 语句
try-finally 语句无论是否发生异常都将执行最后的代码。
try:
<语句>
finally:
<语句> #退出try时总会执行
例子:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
finally:
print "Error: 没有找到文件或读取文件失败"