Hi! Ima beginner, and I recently made a piece of code. But I got no idea WHAT I did wrong! Please help
#include <iostream>
#include <string>
int main(void)
{
using std::cout;
using std::cin;
using std::string;
string text;
int number;
cout << "Type in the string-- ";
cin >> text;
cout << "Now enter a number-- ";
cin >> number;
cout << text.c_str() << number;
return 0;
}
Type in the string-- Hello Friend
Now enter a number-- Hello0
That's the output, right above this. Sometimes it just closes! Any suggestions? The point of this program is to, firstly, prompt you for a string, after you type it in, it then prompts you to enter a number, the output is SUPPOSED to show your string combined with the number you chose. But UNFORTUNATELY, it didn't WORK! Any suggestions please?
Well, I am pretty new to C++. But here's my best to help you out. From what I understand, your program seems to consider your input as multiple variables. By that, I mean: when you enter "Hello Friend". It stores Hello into the string (text) and then Friend into the integer (number). Hence the number 0.
The reason why your program is just randomly closing is because the program has done what it is asked to do. You ask it to input two data and then output them and that's exactly what it does. One neat trick that they taught us in the beginning of the year was to use the command:
system("pause");
I usually have that around the bottom. You will see it in the example below:
If you use >> to input strings rather than getline it'll only capture anything up to the first space character. The getline function will capture up to the number of characters in the second parameter or the delimiter specified in the option third parameter (default is '\n').
Also, you should be able to output a string without converting it to a C string.
With the C++ iostream library, getline with also work with strings as the first parameter.
Another question. Could you please explain these two functions?
char text[243];
cin.getline(text,243);
I don't get it. What does the number 243 represent?
Um. You will understand it quickly when you get to arrays.
What char text[243] does is the following:
243 is just a random number that I decided to assign. That means that the array (text) will hold up to 243 components. char is the type of array. So, in essence, this array will hold up to 243 characters.
cin.getline will get up to 243 characters and store them in the array (text).
when you cout text, you get all of the characters stored in the array.
This is my understanding of the functions and arrays. There are people on this forum who have a much, much better understanding of how everything works. Also, keep in mind that when you post your code online. Use the code tags:
so have your code be inbetween a [code] and then a /code. Also, make sure that the /code is inside brackets [].