C++primer第五版 编写一段程序读入两个字符串,比较其是否相等并输出结果。如果不相等,输出较大的那个字符串和长度较大的那个字符串

一个字符串比较的简单程序。

string对象相等意味着它们的长度相同且所包含的字符也全都相同。
字符串的比较:
1.如果两个string对象的长度不同,而且较短string对象的每个字符都与较长string对象对应位置上的字符相同,就说string对象小于较长string对象
2.如果两个string对象在某些对应的位置上不一致,则string对象比较的结果其实是string对象中第一对相异字符比较的结果。 

// primer_3_2_2.cpp : Defines the entry point for the application.
// 编写一段程序读入两个字符串,比较其是否相等并输出结果。如果不相等,输出较大的那个字符串和长度较大的那个字符串

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string str1,str2;
	cout << "input two strings: " << endl;
	cin >> str1 >> str2;
	//getline(cin,str1);
	//getline(cin,str2);
	if(str1==str2)
		cout << "the two strings are equal." << endl;
	else
	{
		if(str1>str2)
			cout << '"' << str1 << '"' << "is greater than" << '"' << str2 << '"' << endl;
		else
			cout << '"' << str2 << '"' << "is greater than" << '"' << str1 << '"' << endl;
		if(str1.size()>str2.size())
			cout << '"' << str1 << '"' << "is longer than" << '"' << str2 << '"' << endl;
		else
		{
			if(str2.size()>str1.size())
				cout << '"' << str1 << '"' << "is longer than" << '"' << str2 << '"' << endl;
			else
				cout << "the two strings of " << "'" << str1 << "'" << " and " << "'" << str2 << "'" << " have the same length " << endl;
	
		}
	}
	system("pause");
	return 0;
}

在“input two strings”的提示下,输入

hello

better

敲回车,就会出现以下结果:

注意,用cin读入字符串时,是不能有空格的,如果出现空格,便会当成两个字符串处理,例如输入“hello world”,它就会自动将“hello”赋给str1,将“word”赋给str2。例如

如果我们需要比较一行字符串,则应该使用getline函数。 即将cin行代码注释掉,将getline两行代码解注释,如下:

//cin >> str1 >> str2;
getline(cin,str1);
getline(cin,str2);

但是这里要提醒一下,getline将换行符也读进来了,因此输入两行字符串后敲回车并不会立刻产生结果,需要再敲一个回车才能打印出来。例如

猜你喜欢

转载自blog.csdn.net/elma_tww/article/details/82154155
今日推荐