第三章 字符串、向量和數組
阿新 • • 發佈:2017-10-04
5-0 get main 運算符 using else 3.3 stream 一次
3.2
1 #include <iostream> 2 #include <string> 3 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 using std::string; 8 9 int main() 10 { 11 string line; 12 while (getline(cin, line)) 13 cout << line << endl; 14 return 0; 15 }一次讀入一行
1 #include <iostream> 2 #include <string> 3 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 using std::string; 8 9 int main() 10 { 11 string word; 12 while (cin >> word) 13 cout << word << endl; 14 return 0; 15 }一次讀入一個單詞
3.3
輸入運算符:自動忽略string類對象開頭的空白(即空格符、換行符、制表符等),並從第一個真正的字符開始讀起,直到遇見下一處空白為止。
getline函數:從給定的輸入流中讀入內容,直到遇到換行符為止(換行符也被讀進來了),然後把所讀的內容存入到那個 string 對象中去(不存換行符)。
3.4
1 #include <iostream> 2 #include <string> 3 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 using std::stringView Code; 8 9 void is_equal(string &s1, string &s2) 10 { 11 if (s1 == s2) { 12 cout << s1 << " is equal to " << s2 << endl; 13 } 14 else { 15 if (s1 < s2) cout << s1 << " is smaller than " << s2 << endl; 16 else cout << s1 << " is bigger than " << s2 << endl; 17 } 18 } 19 20 void is_same_length(string &s1, string &s2) 21 { 22 if (s1.size() == s2.size()){ 23 cout << s1 << "‘s length is equal to " << s2 << endl ; 24 } 25 else { 26 if (s1.size() < s2.size()) cout << s1 << "‘s length is shorter than " << s2 << endl; 27 else cout << s1 << "‘s length is longer than " << s2 << endl; 28 } 29 } 30 31 int main() 32 { 33 string s1, s2; 34 cin >> s1 >> s2; 35 is_equal(s1, s2); 36 is_same_length(s1, s2); 37 return 0; 38 }
3.5
1 #include <iostream> 2 #include <string> 3 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 using std::string; 8 9 void solve1() 10 { 11 string s1, s2 = ""; 12 while (getline(cin, s1)) { 13 s2 += s1; 14 cout << s2 << endl; 15 } 16 } 17 18 void solve2() 19 { 20 string s1, s2 = ""; 21 while (getline(cin, s1)) { 22 s2 = s2 + s1 + " "; 23 cout << s2 << endl; 24 } 25 26 } 27 28 int main() 29 { 30 solve1(); 31 solve2(); 32 return 0; 33 }View Code
第三章 字符串、向量和數組