ZZ: C++实现读取整行文本和每次只读入一个单词

预备知识:
1.四种初始化string对象的方式: string s1; //默认构造函数,s1为空串 string s2(s1); //将s2初始化为s1的一个副本 string s3("value"); //将s3初始化为一个字符串字面值副本 string s4(n,'c'); //将s4初始化为字符'c'的n个副本 2.endl:用来输出一个换行符并刷新输出缓冲区 3.getline(cin,line):getline函数从标准输入从读取一行文本放入line字符串中 4.s.empty() //如果s为空串,则返回true,否则返回false 5.s.size() //返回s中字符的个数,其返回的类型是string::size_type,而非int. 程序清单1(实现每次从标准输入读入一个单词): #include <iostream> #include <string> using namespace std; int main(int argc,char *argv[]) { string word; while(cin >> word) { cout<<word<<endl; //endl用来输出一个换行符并刷新输出缓冲区 } return 0; }
编译源程序: g
++ -o string string.cpp 执行程序: ./string 执行结果: hello hello love love i love you i love you 程序清单2(实现每次读取一行文本): #include <iostream> #include <string> using namespace std; int main(int argc,char *argv[]) { string line; while(getline(cin,line)) { cout<<line<<endl; } return 0; }
编译源程序: g
++ -o string2 string2.cpp 运行程序: ./string2 运行结果: hello hello love love i love you i love you The only girl I care about has gone away. The only girl I care about has gone away. 程序清单3(string的size和empty操作): #include <iostream> #include <string> using namespace std; int main(int argc,char *argv[]) { string str1; string str2("I love you!"); if(str1.empty()) { cout<<"str1 is empty."<<endl; } cout<<"The size of "<<str2<<" is "<<str2.size()<<" characters."<<endl; return 0; }
编译源程序: g
++ -o string3 string3.cpp 执行程序: ./string3 执行结果: str1 is empty. The size of I love you! is 11 characters. 注意: string的size操作返回的结果是size_type类型,不是int型!如果在程序清单3中加入如下一条语句: int num = str2.size(); 编译程序将报错: error: argument of type ‘size_t (std::basic_string<char, std::char_traits<char>, std::allocator<char> >::)()const’ does not match ‘int
原文地址:https://www.cnblogs.com/DuSizhong/p/2916425.html