C ++ Primer第5版字符串练习要求提供相同输出的两段不同代码?

时间:2015-04-07 21:27:39

标签: c++ string

在C ++ Primer字符串章节的练习中,方向如下:

  

编写程序以读取两个字符串并报告字符串是否为   等于。如果没有,请报告两者中哪一个更大。现在,改变   程序报告字符串是否具有相同的长度,如果   不,报告哪个更长。

我写的:

#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()进行比较。我打印出尺寸和.length(),我得到了相同的答案,所以我想知道我是否误解了这个问题,还是表明长度和尺寸真的是一样的?

1 个答案:

答案 0 :(得分:4)

string :: size和string :: length都是同义词并返回完全相同的值。  参考http://www.cplusplus.com/reference/string/string/length/

相关问题