简体   繁体   English

C ++行输出

[英]C++ line output

cout << boolalpha ("1" < "0") << endl;

I was compiling this recently as a spin off from some course work I was doing. 我最近正在编写这篇文章,作为我正在做的一些课程工作的分支。 Why does this produce true when I execute it? 当我执行它时,为什么这会产生true

cout << boolalpha (string("1") < string("0")) << endl;

does the comparison as expected. 按预期进行比较。

It's comparing const char* , the result of "1" and "0" is undefined by the standard, whereas the comparison of 2 std::string s is defined and your output in that case is expected. 它是比较const char* ,标准未定义"1""0"的结果,而定义了2 std::string s的比较,并且在这种情况下输出是预期的。

Quick case in point: 快速案例:

char* y = "0";
char* x = "1";
std::cout << (x<y) << endl;
    //output 1 on my platform

and

char* x = "1";
char* y = "0";
std::cout << (x<y) << endl;
    //output 0 on my platform

I'm specifying "on my platform" because there's no standard rule (but it can be a compiler rule) to where the pointers are created or in which order they are created. 我正在指定“在我的平台上”,因为没有标准规则(但它可以是编译器规则)指向创建指针的位置或创建指针的顺序。

In my case, the addresses are assigned in reverse order of declaration. 就我而言,地址的分配顺序与声明的顺序相反。

I'm willing to bet that if you run: 我愿意打赌,如果你跑:

cout << ("1" < "0") << endl;

and

cout << ("0" < "1") << endl;

you'd get the same output (although it's not a rule). 你得到相同的输出(虽然这不是一个规则)。 Note that you should run them in different instances of the program. 请注意,您应该在程序的不同实例中运行它们。 If you run them in the same instance, you might get different results, as string literals reside in a single place in memory. 如果在同一实例中运行它们,则可能会得到不同的结果,因为字符串文字位于内存中的单个位置。

Expression "1" < "0" compares values of two pointers. 表达式“1”<“0”比较两个指针的值。 One points to character sequence "1" and the other points to character sequence. 一个指向字符序列“1”,另一个指向字符序列。 Your compiler placed character sequences in memory in such a way that address of char sequence "1" is before that of "0". 您的编译器将字符序列放在内存中,使char序列“1”的地址在“0”之前。

With strings, however, operator<(const string&, const string&) is called, as expected. 但是,对于字符串,将按预期调用operator <(const string&,const string&)。

Because you are comparing two pointers (the strings "1" and "0" are represented as arrays of char , synonymous (kinda) with pointer to char). 因为你正在比较两个指针(字符串"1""0"表示为char数组,synonymous(kinda)表示char指针)。 If you want the comparison between the numbers 0 and 1, you don't need the quotes. 如果要比较数字0和1,则不需要引号。 Otherwise you need a string comparison function that compares the content of the strings, not their addresses. 否则,您需要一个字符串比较函数来比较字符串的内容,而不是它们的地址。 Best if you wrap them in an std::string and use the compare() member function. 最好是将它们包装在std::string并使用compare()成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM