Strings Greater then

closed account (EwCjE3v7)
Hi there,
Can someone tell me why slang is greater then str and phrase. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>
using std::cin; using std::string; // <- sorry I have to use these
using std::cout; using std::endl;

int main()
{
    string str = "Hello";
    string phrase = "Hello World";
    string slang = "Hiya";
    if (slang > str) { // true Why?
        std::cout << slang << endl;
    }


    return 0;
}



Also i just came across this
#include <iostream>
1
2
3
4
5
6
7
8
9
10
11
12
13
using std::cin; using std::string; // <- sorry I have to use these
using std::cout; using std::endl;

int main()
{
    string s1 = "hello", s2 = "world";
    string s3 = '1' + ", " + s2 + '\n';
    s1 += s2;
    cout << s3; // output is @world why


    return 0;
}

Why is output @world?
Last edited on
Think of the order you would find the words in a dictionary. If the first letters are the same then the second letters are compared (and so on). In this case "i" comes after "e" so the string is considered "greater".

(but beware of upper-case and lower-case letters when using the dictionary analogy).
Last edited on
closed account (EwCjE3v7)
@Chervil oh
now i get it. Thanks great help i just edited can you please also answer my second question if you can. Thanks

Also i just came across this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using std::cin; using std::string; // <- sorry I have to use these
using std::cout; using std::endl;

int main()
{
    string s1 = "hello", s2 = "world";
    string s3 = '1' + ", " + s2 + '\n';
    s1 += s2;
    cout << s3; // output is @world why


    return 0;
}


Why is output @world?
> Why is output @world?

Undefined behaviour.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using std::cin; using std::string; // <- sorry I have to use these
using std::cout; using std::endl;

int main()
{
    string s1 = "hello", s2 = "world";

    string s3 = '1' + ( ", " + s2 ) + '\n'; // fine, ( ", " + s2 ) is a std::string
    cout << s3; // output is: 1, World

    // out of bounds access of array (binay + associates to the left)
    // size of array ", " (literal) is 3; value of '1' is greater than 3
    // '1' + ", " tries to access an address beyond the end of the literal array.
    string s4 = '1' + ", " + s2 + '\n'; // ***error: results in undefined behaviour
                                         // all bets are off now.
}
Topic archived. No new replies allowed.