你如何比较C ++中的多个字符串

时间:2014-03-16 07:43:30

标签: 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)

1 个答案:

答案 0 :(得分:1)

试试这个

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;
}