如何比较字符串形式的临时变量
How to compare the temporary variables in the form of string?
我想知道为什么两个结果不同?
代码为:
string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;
输出为:
1 0
C++中的文字字符串实际上是常量字符的数组。与任何其他数组一样,它们衰减为指向其第一个元素的指针。
使用 "35">"255"
您可以比较指针,而不是字符串本身的内容。
要比较文字字符串,您需要使用 std::strcmp
.但请注意,它不返回布尔值。
您当前所做的大致相当于
char const* a = "35";
char const* b = "255";
std::cout << (&a[0] > &b[0]) << 'n'; // Print the result of comparing the *pointers*
使用 s1>s2
调用 std::string
的 operator>
函数。表达式 s1 > s2
等效于 s1.operator>(s2)
。
因为"35"和"255"不是std::string,所以它是一个const char[](即字符数组(。当您声明 s1 和 s2 时,const char[] 将转换为 std::string,因为 s1 和 s2 的类型是 std::string,但它不会自动执行此操作。
运行cout << (s1>s2) << " " << (string("35") > string("255")) << endl
应按预期工作。
您可以使用 strcmp((,它根据字符串的比较返回正值或负值。
在这里查看手册:strcmp((
请注意,它采用常量字符*而不是字符串作为参数。
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 从字符串变量中逐字符读取单词
- 对函数 PlaySound 使用字符串变量
- C++中的字符串变量
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 如何使用C++将字符串中的字符转换为整数变量
- 字符串变量,比如说"字符串str",可以直接复制到数组中吗?
- 我可以用字符串变量而不是它的名字创建容器吗? C++
- 字符串变量的大小
- 使变量字符串忽略转义序列
- 如何在 C 宏中将变量字符串与文字字符串连接起来?
- 在 Py_BuildValue 中返回变量字符串
- 如何将字符串作为变量与另一个变量字符串进行比较
- 从变量字符串中提升文件系统路径
- 用变量字符串声明设置容器
- 通过变量(字符串)调用obejct和方法
- C++创建文本和变量字符串
- 如何在循环中使用变量字符串