C++输入总结

点击关注:阿里云科技快讯,有机会获得精美礼品!

__20180814165147

总结下在编程题中的输入数据方法

#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;
}

__20180814165122
我,阿里云科技快讯!横着走,请关注我好吗QAQ

猜你喜欢

转载自yq.aliyun.com/articles/625257