总结下在编程题中的输入数据方法
- #include <iostream>
- using namespace std;
- int main(){
- int n;
- cin>>n;
- string s;
- // 注意, 在 VS 中这里会报错, 需要添加 #include<string>
- // 因为在 iostream 里, 对 string 只是声明, 并没有定义.
- cin>>s;
- // 但是上面碰到空格会进行分段, 如果想一次性输入整行;
- // 会截断回车符.
- // 如果没有读入字符, 将返回 false;
- getline(cin,line);
- // 如果想使用自定义分隔符
- getline(cin,line,delime);
- while(getline(cin,tt,delime)){
- process(tt);
- }
- // 注意 如果之前有 cin, 然后再进行 getline 之前, 需要把 cin 没有处理的回车符处理掉,
- // 也就是在 getline 之前加个
- cin.get();
- // 如果想从一个字符串里读取数据
- #include<sstream>
- string src("dasf");
- string des;
- stringstream ss(src);
- getline(ss,des,delime);
- }
字符串转数字, 数字转字符串
- #include <iostream>
- #include <string>
- using namespace std;
- // string 里有 to_string() 这个函数 参数可以是 int,long,long long,unsigned long,float,double,long double;
- int main(){
- int a = 1;
- long b = 12345;
- unsigned int c = 23;
- float d = 32.123;
- double e = 12.1223;
- cout<<to_string(a)<<""<<to_string(b)<<" "<<to_string(c)<<" "<<to_string(d)<<" "<<to_string(e)<<endl;
- return 0;
- }
字符串转数字
两种方法, 第一种就是调用 string 自带的 stoi,stol,stoul,stoll,stoull,stof,stod,stold 等.
第二种就是把字符串转换成 stringstream, 然后用 >> 进行读取
- #include <iostream>
- #include <string>
- template<typename out_type,typename in_value>
- out_type convert(const in_value& t){
- stringstream stream;
- stream<<t;
- out_type result;
- stream>>result;
- return result;
- }
- int main(){
- string a("1234");
- string b("12.45");
- cout<<stoi(a)<<" "<<stof(b)<<endl;
- stringstream s1(a);
- int a1;
- s1>>a1;
- cout<<a1<<endl;
- // 注意如果多个字符串进行输入到 stringstream 时, 先 clear 一下, 把缓冲区清空.
- s1.clear();
- float a2 = convert<float>(b);
- cout<<a2<<endl;
- }
来源: https://yq.aliyun.com/articles/625257