c++ - 你如何在 C++ 中比较多个字符串

标签 c++ string if-statement

我正在处理一项硬件作业,但我卡在了这部分。 这是代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;


std::string stringSmallest(std::string s1, std::string s2, std::string s3, std::string s4, std::string s5 );


int main(int argc, char)
{
   std::string sSmallest = stringSmallest("hi", "wassup", "hello", "good","bye");
    printf("strings: %i", sSmallest); 
    std::cin.get();
    return 0;
}

std::string stringSmallest(std::string s1, std::string s2, std::string s3, std::string s4, std::string s5 ){
    std::string strSmallest = 0;
    if (strSmallest.compare(s1)<0)
        strSmallest = s1;

    if (strSmallest.compare(s2)<0)
        strSmallest = s2;

    if (strSmallest.compare(s3)<0)
        strSmallest = s3;

    if (strSmallest.compare(s4)<0)
        strSmallest = s4;

    if (strSmallest.compare(s5)<0)
        strSmallest = s5;

    return strSmallest;
}

我想做的是用最小的字符串创建一个字符串。 最小 = 最小(s1, s2, s3, s4, s5)

最佳答案

试试这个

std::string stringSmallest(std::string s1, std::string s2, std::string s3, std::string s4, std::string s5 )
{
std::string strSmallest = s1;

if (strSmallest.compare(s2)>0)
    strSmallest = s2;

if (strSmallest.compare(s3)>0)
    strSmallest = s3;

if (strSmallest.compare(s4)>0)
    strSmallest = s4;

if (strSmallest.compare(s5)>0)
    strSmallest = s5;

return strSmallest;
}

关于c++ - 你如何在 C++ 中比较多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434299/

相关文章:

没有 libstdc++ 的 C++ RTTI。可能吗?

c++ - 将系统命令的输出存储到 c 中的本地字符数组中

python - 为什么 str.count ('' ) 和 len(str) 给出不同的输出?

swift - 我怎样才能用当前时间计算一些位置的打开和关闭时间

r - 根据 R 中另一行的条件改变新列

c++ - 使用类成员函数作为回调

java - 用键值对分隔字符串

MySQL 替换数据库的每个表和列中的字符

php - 在 PHP 中使用多个 elseif 嵌套循环的替代方法是什么

c++ - 无法理解 C++ `virtual`