
练习3.2
一次读入一整行:
#include <iostream>
using namespace std;
#include <string>
int main() {
string line;
getline(cin,line);
cout << line << endl;
return 0;
}

一次读入一个词:
#include <iostream>
using namespace std;
#include <string>
int main() {
string word;
cin >> word;
cout << word << endl;
return 0;
}

练习3.3
-
string类型自动忽略开头的空白(即空格符、换行符、制表符等)并从第一个真正的字符开始读起,知道遇见下一处空白为止。
比如,如果程序的输入是“ Hello World! ” (注意开头和结尾处的空格),则输出为“Hello”,输出结果中没有任何空格。

-
getline()函数的参数是一个输入流和一个string对象,函数从给定的输入流中读入内容,直到遇到换行符为止(注意换行符也读进来了),然后把所读的内容存入到那个string对象中去(注意不存换行符)。getline 函数只要一碰到换行符就结束读取操作并返回结果,哪怕输入的一开始就是换行符也是如此。如果输入真的一开始就是换行符,那么所得的结果就是一个空string。因此,输入中有空格没有关系,输出的时候也会保留这个空格。比如,输入“ Hello World! ”,会输出一行一样的。

练习3.4
#include <iostream>
using namespace std;
#include <string>
int main() {
string word1,word2;
cin >> word1 >> word2;
if (word1 == word2)
cout << "word1 is equal to word2" << endl;
else if (word1 > word2)
cout << "The larger one is " << word1 << endl;
else
cout << "The larger one is " << word2 << endl;
return 0;
}


练习3.5
连接成大字符串:
#include <iostream>
using namespace std;
#include <string>
int main() {
string word;
while (cin >> word)
cout << word ;
return 0;
}

分隔字符串:
#include <iostream>
using namespace std;
#include <string>
int main() {
string word;
while (cin >> word)
cout << word << " ";
return 0;
}

这篇博客探讨了C++中的输入输出流,包括如何使用getline()读取整行和使用cin读取单个单词。它强调了string类型的特性,如自动忽略开头的空白以及getline()函数的工作原理,它读取直到遇到换行符。此外,还展示了比较两个单词大小的示例以及如何连续读取和输出多个单词,以及如何在输出时分隔它们。
2万+

被折叠的 条评论
为什么被折叠?



