C++_auto

来源:互联网 发布:淘宝账号已被限制登录 编辑:程序博客网 时间:2024/06/05 11:47
    1.
#include <iostream>#include <string>using namespace std;int main(int argc, char const *argv[]){    string line;    getline(cin,line);    for(auto &c:line)        c='X';    cout<<line;    cout<<line<<endl;    return 0;}

这里的for语句为C++11新定义的范围for语句。
注意:
1. 利用auto关键字推断字符串中每一个元素的类型;
2. c必须定义为引用类型,否则无法修改字符串的内容。
这里将字符串line中的所有字符变为‘X’,输出结果为:

What is your name?XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX--------------------------------Process exited with return value 0Press any key to continue . . .
  1. 读入一个包含标点符号的字符串,将标点符号去除后输出。

第一种:

#include <iostream>#include <string>using namespace std;int main(int argc, char const *argv[]){    string line;    getline(cin,line);    for(auto &c:line)    {        if(!ispunct(c))            cout<<c;    }    cout<<endl;    return 0;}

这里的ispunct(char ch)函数,如果参数ch是除字母,数字和空格外可打印字符,函数返回非零值,否则返回零值。
这里的punct为punctuation(标点符号)的缩写。
由此想到另一个函数,isspace(char ch),若判断字符ch为空格、制表符或换行符,函数返回非零值,否则返回零值。

what,is.your?name!whatisyourname--------------------------------Process exited with return value 0Press any key to continue . . .

第二种:

#include <iostream>#include <string>using namespace std;int main(int argc, char const *argv[]){    string line,result="";    getline(cin,line);    for(decltype(line.size()) i=0;i<line.size();i++)    {        if(!ispunct(line[i]))            result+=line[i];    }    cout<<result<<endl;    return 0;}

decltype 类型说明符生成指定表达式的类型。在此过程中,编译器分析表达式并得到它的类型,却不实际计算表达式的值。
详细用法见:
http://blog.csdn.net/yhl_leo/article/details/50865552

输出结果:

what,is.your?name!!whatisyourname--------------------------------Process exited with return value 0Press any key to continue . . .
原创粉丝点击