Hi first of all I'd like to say I'm completely new to C++ in fact apart from very little pascal and tiny bit of assembler I did 30 years ago I'm pretty new full stop. I am about 8 hrs in so forgive me for this maybe obvious question. I was trying to add a string then a character then another string into the same result string but it wouldn't work on the same line I had to do it one line at a time is this correct or can the strings and characters be combined on the same line
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string answer = "";
Char keypress;
/* A) this works to output to the console */
cout "You pressed the " << keypress << " key" << endl;
/* B) does not work */
answer = "You pressed the" + keypress + " key";
/* C) This is fixed by doing the following */
answer += "You pressed the ";
answer += keypress;
answer += " key";
cout << answer << endl;
Option A works outputting to the console, option B does not work trying to add strings and characters and option C works, do I always have to add them on separate lines or am I missing something? Can I not combine strings and characters on the same line?
That's because the string literals you use are C-strings, which are technically pointers to char arrays.
Let's examine the expression
"hell" + 'o'
"hell" is in merely a pointer to an array with the first char 'h', it's a memory address.
If you now try to add 'o' (ASCII code 111) to this, all you do is, moving the pointer 111 addresses ahead so the c-string points not anymore to the right place.
But concatenating std-strings (and std-string + c-string) is possible because the opererator + is overloaded for std-strings.
All you need to do is, converting your char to an std-string before concatenating:
It is always better to post enough of the program that is compilable and able to test. This way no one has to guess at what is missing. Also what you left out could be a problem that you do not know about yet.
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
int main()
{
std::string answer; // <--- Empty when defined. Does not need initialized.
char keypress{}; // <--- A good idea to initialize, but not really necessary in this case.
std::cout << "\n Press a key then press \"Enter\": ";
std::cin >> keypress;
/* A) this works to output to the console */
std::cout << "You pressed the " << keypress << " key" << '\n'; // <--- Missed the insertation operator, (<<), at the beginning.
/* B) does not work */
//answer = "You pressed the" + keypress + " key";
// C) This is fixed by doing the following. This works, but A is shorter.
answer += "You pressed the ";
answer += keypress;
answer += " key";
std::cout << answer << '\n';
// <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue: ";
std::cin.get();
return 0; // <--- Not required, but makes a good break point.
}
In line 9 it is "char" not "Char". if "Char" did not produce an error at compile time then the compiler may need to be changed to be more strict about errors or warnings. Or you may have included a header file that defines "Char", but that may be for something else.
"char" is a fundamental type to define a variable type.
Making this change allows line 15 to work properly.
"B" will work as answer = "You pressed the" + keypress;, but when adding + " key"; became the problem and I am not sure why yet.
"C" works, but "A" is shorter when "keypress" is defined with the proper type.
I added lines 11 and 12 because I think that is what you wanted. At least it gave some verity over just initializing "keypress" to one letter.
Thank you all for your replies that was most helpful I'm sure I'll have many more questions on this forum
Here's one for example I see that you are typing std:: in your code the book I'm reading uses
using namespace std;
at the start of each program and does not use the std:: is it best practice to code using std:: and/or is there are reason why you don't use the namespace command and then not type the std::?
Hi Brian, I am very much a beginner like yourself, so don't trust what I am saying too much. I just like to read through these questions to learn more. However, I believe others do not use the std namespace as well as others namespaces as they include many functions which could be named the same as a function you have created, which could cause a issue.
For instance if just for talking sake, the namespace has a function called bah and you have created one called bah, the compiler could be calling the wrong one without you even knowing, so the program could be running incorrectly
That's a pretty good beginner's explanation. You have picked things up well.
@BrianD,
To echo, possibly clarify, what @DonnaPin wrote, the usingnamespace std; command pulls all of the std:: library symbols into the global namespace, obviating the benefits of namespaces. Note that doing this in a header (.h) file is extremely more problematic than in a source (.cpp) file, but is not recommended in a source file either for the reasons already mentioned.
If you want to use specific symbols without the namespace prefix, consider instead
"B" will work as answer = "You pressed the" + keypress;, but when adding + " key"; became the problem and I am not sure why yet.
B will compile without +" key" - but doesn't do what you think it does. It takes the memory address of "You pressed..." and adds the value of keypress to get a new memory address. The contents of this memory up to a null are then assigned to answer - whatever happens to be at that memory address.
When adding + " key" you are trying to add a memory address to a memory address which isn't supported.