2015-04-07 31 views
-1

在這個練習中,從C++入門弦章,方向閱讀:C++ Primer 5th Edition字符串練習要求提供相同輸出的兩段不同代碼段?

編寫一個程序來讀取兩個字符串,並報告字符串是否 相等。如果沒有,報告哪兩個更大。現在,將 程序更改爲報告字符串是否具有相同的長度,如果不是 ,則報告哪個更長。

對此我寫道:

#include <iostream> 
#include <string> 
using std::string; 
using std::cin; 
using std::cout; 
using std::endl; 


/* Write a program to read two strings and report whether the 
strings are equal. If not, report which of the two is larger. Now, change 
the program to report whether the strings have the same length, and if 
not, report which is longer. */ 


int main() 
{ 
    string line; 
    string word; 
    getline(cin, line); 
    getline(cin, word); 

    if (line == word) { 
     cout << "String are equal." << endl; 
    } 
    else { 
     if (line > word) 
      cout << line << " is longer." << endl; 
     else { 
      cout << word << " is longer." << endl; 
     } 

    } 

    return 0; 
} 

這似乎對這個問題的工作。現在的第一個例子:

編寫一個程序來讀取兩個字符串並報告字符串是否爲 等於。如果沒有,報告哪兩個更大。

我改變了比較有.size(),併爲這一個:

編寫一個程序來讀取兩個字符串,並報告字符串是否 相等。如果沒有,報告哪兩個更大。

我刪除了用於比較的.size()。我打印出size和.length(),並且我得到了相同的答案,所以我想知道是否我誤解了這個問題,或者是否顯示長度和大小真的是一回事?

+3

「greater」='strcmp'(或任何C++等價物),「longer」='strlen'(或任何C++等價物) –

+0

'std :: string :: size()'和'std :: string :: length()'是一樣的。 – juanchopanza

+0

那麼這真的是這個問題試圖教導什麼? – user3099345

回答

相關問題