C++ single quotes syntax - c++

I am learning C++ and just started reading "Programming Principles and Practice" by Bjarne Stroustrup and he uses this code to illustrate a point:
#include "std_lib_facilities.h"
using namespace std;
int main() // C++ programs start by executing the function main
{
char c = 'x';
int i1 = c;
int i2 = 'x';
char c2 = i1;
cout << c << ' << i1 << ' << c2 << '\n';
return 0;
}
I am familiar in general with the difference between double and single quotes in the C++ world, but would someone kindly explain the construction and purpose of the section ' << i1 << '
Thanks

cout << c << ' << i1 << ' << c2 << '\n';
appears to be a typo in the book. I see it in Programming Principles and Practice Using C++ (Second Edition) Second printing. I do not see it listed in the errata.
According to the book, the intended output is
x 120 x
But what happens here is ' << i1 << ' attempts to compress the << i1 << to a multi-byte character and prints out an integer (most likely 540818464-> 0x203C3C20 -> ASCII values of ' ', '<', '<', ' ') because cout doesn't know wide characters. You'd need wcout for that. End result is output something like
x540818464x
and a warning or two from the compiler because while it's valid C++ code, it's almost certainly not what you want to be doing.
The line should most likely read
cout << c << ' ' << i1 << ' ' << c2 << '\n';
which will output the expected x 120 x
In other words, Linker3000, you are not crazy and not misunderstanding the example code.
Anyone know who I should contact to log errata or get a clarification on the off chance there is some top secret sneakiness going way over my head?

Before answering your question, here is a little background on what that is actually doing. Also note that there is a typo in the example, the string constant should have been double quoted:
cout << c << " << i1 << " << c2 << "\n";
In C++, operators can be overloaded so that they mean different things with different functions. In the case of cout, the << operator is overloaded as the "Insertion Operator". Think of it as taking the operand on the right, and inserting it (or sending it) into the operator on the left.
For example,
cout << "Hello World";
This takes the string "Hello World", and sends it to cout for processing.
So what beginners do not get is what something like this means:
cout << "Hello" << " World";
This is doing the same thing, but the operator precedence says to perform the injections from left to right. To make this work, the cout object returns itself as a function return value. Why is this important? Because the above statement is actually two separate operator evaluations:
(cout << "Hello") << " World";
This first injects "Hello" to cout, which outputs it, then continues to evaluate the next inject operator. Because cout returns itself, after the (cout << "Hello") is executed you have the following still to be evaluated:
cout << " World";
This expression injects " World" into the cout object, which then outputs " World", with the net effect being that you see "Hello World" just like the first time.
So in your example, what is it doing?
cout << c << " << i1 << " << c2 << "\n";
This is evaluated left to right as follows:
((((cout << c) << " << i1 << ") << c2) << "\n"); => Outputs value of c
((((cout ) << " << i1 << ") << c2) << "\n"); => Outputs string " << i1 << "
((( cout ) << c2) << "\n"); => Outputs value of c2
(( cout ) << "\n"); => Outputs newline character
( cout ); => No more output
Expression completes and returns the cout object as the expression value.
Assuming c='x' and c2='x', the final output from this expression is the following character string output on a single line:
x << i1 << x
For beginners, all those insertion operators << look a little strange. It is because you are dealing with objects. You could build the string up as a complete formatted object before injecting it into cout, and while that make the cout expression look simpler, we do not do that in C++ because it makes your code more complex and error prone. Note also, there is nothing special about the cout object. If you wanted to output to the standard error stream, you would use cerr instead. If you wanted to output to a file, your would instantiate a stream object that outputs to the desired file. That rest of the code in your example would be the same.
In C, the same thing would be done procedurally using a format string:
printf("%d << i1 << %d\n", i1, c2);
This is allowed in C++ too, because C++ is a superset of C. Many C++ programmers still use this output method, but that is because those programmers learned C first, and may not have fully embraced the object oriented nature of C++
Note that you may also have seen the << operator in the context of mathematical expressions like:
A = A << 8;
In this case, the << operator is the bitwise rotate operation. It has nothing to do with output to cout. It will rotate the bits in A to the left by eight bits.

Related

C++ display text left and right in same row

I want to output a whole formatted console line (80 characters) in C++.
It should look like this:
Some things on the left side some other on the right side
The data contains two iterator functions that return std::string and fixed texts. Something like this:
std::cout << (*some_iterator)->getID() << " some text:" << LOTSOFSPACES << (*some_other_iterator)->getName() << " some more text.";
Outcome should always be 80 characters.
I tried messing around with std::setw and std::setfill, std::left and std::right, using a stringstream and calculating the spaces I have to create. But nothing really works and most ideas just destroyed the output completely.
Any ideas? Unfortunately I am not allowed to use external libraries.
If you can tell for sure both parts are always less than 40 characters (or they can be split in two columns in any other way), you could do it like this:
std::string firstPart = (*some_iterator)->getID() + " some text:";
std::string secondPart = (*some_other_iterator)->getName() + " some more text.";
std::cout << std::setw(40) << std::left << firstPart
<< std::setw(40) << std::right << secondPart;
See it online
More versatile solution would be to simply calculate the spacing between strings and insert it manually. This doesn't require having columns of known length:
std::string firstPart = (*some_iterator)->getID() + " some text:";
std::string secondPart = (*some_other_iterator)->getName() + " some more text.";
std::size_t spacingSize = 80 - firstPart.length() - secondPart.length();
//Add some code to check if spacingSize is not negative!
std::cout << firstPart << std::string(spacingSize, ' ') << secondPart;
See it online
You can try to set the coursor at the position.
First you have to add library:
#include <windows.h>
Now you can use function:
COORD c;
c.X = x_coordinate;
c.Y = y_coordinate;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);

C++11 type-conversion heisenbug when using std::string::c_str()

This is very strange.
OSX 10.10
LLVM 6.0
XCode 6.1
test_assert("Wierd", String{"ABC"}, "ABC" ); // claims not equal
String is my custom class (wrapping a Python String primitive), and it should pass this test.
Here's test_assert, with added debug output:
template <typename B, typename V>
static void test_assert( std::string description, B benchmark, V value )
{
std::ostringstream full_description;
full_description << description
<< " : { " << "benchmark" << ", " << "value" << " }"
<< " = { " << typeid(B).name() << ", " << typeid(V).name() << " }"
<< " , { " << benchmark << ", " << value << " }";
// N2Py6StringE, PKc i.e. Py::String and const char* (Pointer to Konst Char)
std::cout << typeid(B).name() << ", " << typeid(V).name() << std::endl;
V b_as_v{static_cast<V>(benchmark)};
// wtf? b_as_v: \352\277_\377 -- should be "ABC"
std::cout << "b_as_v: " << b_as_v << std::endl; // Y
if( b_as_v == value )
std::cout << " PASSED: " << full_description.str() << std::endl;
else
throw TestError( full_description.str() );
}
It is this b_as_v{static_cast<V>(benchmark)}; that is throwing me, because if I single step into it, it correctly takes me to String's 'convert to const char*' operator, which performs its duty correctly:
class String : Object {
explicit operator const char*() const
{
std::string s{ as_std_string() };
const char* c{ s.c_str() };
// c before return: ABC
std::cout << "c before return: " << c << std::endl; // X
return c;
}
:
Now this is the weird thing: if line X is in place, line Y reports nothing: 'b_as_v: '
Removing it, line Y reports the original: 'b_as_v: \352\277_\377'
In fact, just printing std::cout << std::endl; // X' for X is sufficient to clear output from Y (however, moving X' to immediately in front of Y restores the original behaviour).
So it seems that the act of observation modifies the return value.
A heisenbug >:|
And neither behaviour is the desired one.
Another weirdness is that there is an extra Unicode character that copies to my clipboard at the end of '\352\277_\377' if I copy paste from Xcode's console to the SO text edit window.
Even if I only select the last 7 it still copies across, even though it doesn't take up a whitespace in Xcode's console.
(This extra character doesn't show up on the SO question, in fact it is no longer there when I reopen the question for editing. It isn't a
newline character --I've tested copy-paste-ing in the last character of a particular line)
I have tried to create a testcase, but it performs sadly as I would expect: http://ideone.com/gbyU6Y
A fairly complicated setup, but the cause is rather straightforward:
explicit operator const char*() const
{
std::string s{ as_std_string() };
const char* c{ s.c_str() };
// c before return: ABC
std::cout << "c before return: " << c << std::endl; // X
return c;
}
The pointer returned by std::string::c_str() points into the std::string's internal storage, and so can be invalidated for a number of reasons - the destruction of the std::string object being one of them. Here, c is invalidated as soon as your conversion function returns and s is destroyed, meaning that a dangling pointer is returned.
Also, libc++ uses the small-string optimization, meaning that a string as short as "ABC" is stored inside the std::string object itself (in this case, on the stack), rather than in dynamically allocated storage. This makes it much more likely that the space that used to be occupied by the string could be reused before your code attempt to print it.

custom std::hex manipulator that works for unsigned char

Please consider the following:
unsigned char a(65);
unsigned char z(90);
std::cout << std::hex << a << ", " << z <<std::endl;
Output:
A, Z
But desired output is:
41, 5a
To achieve this I'd like to avoid having to convert values like this, say:
std::cout << std::hex << int(a) << ", " << int(z) <<std::endl;
and instead have some magical manipulator that I can include beforehand:
std::cout << uchar_hex_manip << a << ", " << z << std::endl;
So my question is, how can I define 'uchar_hex_manip' to work as required?
UPDATE: I appreciate all the comments and suggestions so far but I have already said I want to avoid converting the values and no-one seems to have acknowledged that fully. The 'a << ", " << z' I mentioned above is representative of the values to be later streamed in - the actual use case of this in our application is that there is something more complex than that going on where for various reasons it is ideal not to have to shoe-horn in some casts for specific cases.
If you want to print char as hex, you will need to convert it to a an int:
std::cout << std::hex << static_cast<int>('a');
should do the trick.
The reason std::hex doesn't work on char (or unsigned char) is that the stream output operator for char is defined to print the character as the output. There is no modifier to change this behaviour (and although #soon suggests to write your own class - that's a lot of work to avoid a cast).

C++ const casting

I am trying to print the value of a const but it is not working. I am making a return to C++ after years so I know casting is a possible solution but I can't get that working either.
The code is as follows:
//the number of blanks surrounding the greeting
const int pad = 0;
//the number of rows and columns to write
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
cout << endl << "Rows : " + rows;
I am trying to print the value of 'rows' without success.
You want:
cout << endl << "Rows : " << rows;
Note this has nothing to do with const - C++ does not allow you to concatenate strings and numbers with the + operator. What you were actually doing was that mysterious thing called pointer arithmetic.
You're almost there:
cout << endl << "Rows : " << rows;
The error is because "Rows : " is a string literal, thus is a constant, and generally speaking is not modified as you may think.
Going slightly further, you likely used + (colloquially used as a concatenation operation) assuming you needed to build a string to give to the output stream. Instead operator << returns the output stream when it is done, allowing chaining.
// It is almost as if you did:
(((cout << endl) << "Rows : ") << rows)
I think you want:
std::cout << std::endl << "Rows : " << rows << std::endl;
I make this mistake all the time as I also work with java a lot.
As others have pointed out, you need
std::cout << std::endl << "Rows : " << rows << std::endl;
The reason (or one of the reasons) is that "Rows : " is a char* and the + operator for char*s doesn't concatenate strings, like the one for std::string and strings in languages like Java and Python.

Comparing Character Literal to Std::String in C++

I would like to compare a character literal with the first element of string, to check for comments in a file. Why use a char? I want to make this into a function, which accepts a character var for the comment. I don't want to allow a string because I want to limit it to a single character in length.
With that in mind I assumed the easy way to go would be to address the character and pass it to the std::string's compare function. However this is giving me unintended results.
My code is as follows:
#include <string>
#include <iostream>
int main ( int argc, char *argv[] )
{
std::string my_string = "bob";
char my_char1 = 'a';
char my_char2 = 'b';
std::cout << "STRING : " << my_string.substr(0,1) << std::endl
<< "CHAR : " << my_char1 << std::endl;
if (my_string.substr(0,1).compare(&my_char1)==0)
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
std::cout << "STRING : " << my_string.substr(0,1) << std::endl
<< "CHAR : " << my_char2 << std::endl;
if (my_string.substr(0,1).compare(&my_char2)==0)
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
std::cout << "STRING : " << my_string << std::endl
<< "STRING 2 : " << "bob" << std::endl;
if (my_string.compare("bob")==0)
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
}
Gives me...
STRING : b
CHAR : a
NOPE...
STRING : b
CHAR : b
NOPE...
STRING : bob
STRING 2 : bob
WOW!
Why does the function think the sub-string and character aren't the same. What's the shortest way to properly compare chars and std::string vars?
(a short rant to avoid reclassification of my question.... feel free to skip)
When I say shortest I mean that out of a desire for coding eloquence. Please note, this is NOT a homework question. I am a chemical engineering Ph.D candidate and am coding as part of independent research. One of my last questions was reclassified as "homework" by user msw (who also made a snide remark) when I asked about efficiency, which I considered on the border of abuse. My code may or may not be reused by others, but I'm trying to make it easy to read and maintainable. I also have a bizarre desire to make my code as efficient as possible where possible. Hence the questions on efficiency and eloquence.
Doing this:
if (my_string.substr(0,1).compare(&my_char2)==0)
Won't work because you're "tricking" the string into thinking it's getting a pointer to a null-terminated C-string. This will have weird effects up to and including crashing your program. Instead, just use normal equality to compare the first character of the string with my_char:
if (my_string[0] == my_char)
// do stuff
Why not just use the indexing operator on your string? It will return a char type.
if (my_string[0] == my_char1)
You can use the operator[] of string to compare it to a single char
// string::operator[]
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str ("Test string");
int i; char c = 't';
for (i=0; i < str.length(); i++)
{
if (c == str[i]) {
std::cout << "Equal at position i = " << i << std::endl;
}
}
return 0;
}
The behaviour of the first two calls to compare is entirely dependent on what random memory contents follows the address of each char. You are calling basic_string::compare(const char*) and the param here is assumed to be a C-String (null-terminated), not a single char. The compare() call will compare your desired char, followed by everything in memory after that char up to the next 0x00 byte, with the std::string in hand.
Otoh the << operator does have a proper overload for char input so your output does not reflect what you are actually comparing here.
Convert the decls of and b to be const char[] a = "a"; and you will get what you want to happen.
Pretty standard, strings in c++ are null-terminated; characters are not. So by using the standard compare method you're really checking if "b\0" == 'b'.
I used this and got the desired output:
if (my_string.substr(0,1).compare( 0, 1, &my_char2, 1)==0 )
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
What this is saying is start at position 0 of the substring, use a length of 1, and compare it to my character reference with a length of 1. Reference