Hi folks I'm relatively new to this and I'm sorry for posting such a mundane question but I'm writing a VERY simple program to practice the things I've learned so far in the tutorial section,
I think its best to post all the code :
------------------------------------------------------------------------
#include <iostream>
using namespace std;
int perimiter (int x, int y){
return ((x+x)+(y+y));}
int area (int x, int y){
return (x*y);
}
int main()
{
int height;
int width;
char name [30];
cout << "please enter your full name : ";
cin >> name;
cout << "hello " << name << endl;
cout << "Enter the height of your rectangle : ";
cin >> height;
cout <<"\n";
cout << "Enter the width of the rectangle : ";
cin >> width;
int choice;
cout << "enter 1 for the area or 2 for the perimeter (or 3 to exit) : ";
cin >> choice;
if (choice == 1){
goto AREA;}
else if (choice == 2){goto PERIMETER;}
else goto end;
PERIMETER:
cout << "the perimeter is : "<< perimiter (height, width) << "\n";
goto end;
AREA:
cout << "the area is : " << area (height, width)<< "\n";
end:
system ("pause");
the problem is that whenever I enter a name with a space it skips all other inputs and just prints all the outputs and ends the program, this does not happen if I use a name with no spaces
I am using Bloodshed Dev-C++ in windows xp 32
I hope I have made myself clear enough, thanks in advence
ps, I cant seem to get the code /code tags to work so sorry bout the messy post.
I thaught the best aproach ( meaning the only one I'm half way familiar with) would be to create a pointer (char * p1) and point it at the char array
1 2 3 4 5 6 7 8 9 10 11 12
int height;
int width;
char name [30];
char * p1;
p1 = &name;
cout << "please enter your full name : ";
cin >> *p1;
cout << "hello " << name << endl;
however it will not compile.
i get an error saying:
cannot convert 'char (*)[30]' to 'char*' in assignment.
I dont know what I am doing wrong in this case. I realise that there is probably an easier way to do this but I am trying to get to grips with character arrays and It's bugging the hell out of me.
You cannot use plain "cin" as it stops reading when encountering whitespace.
One solution is:
1 2 3 4
char name [30];
cout << "please enter your full name : ";
cin.getline( name,29);
cout << "hello " << name << endl;
An array of chars is a string (old type).
Here:
You declare an array of chars - holds 30 chars.
Using cin.getline - You read the entire line entered including whitespace.
(name, 29) = "name" is where you want the chars stored and "29" is the maximum number allowed to be read.
You might say -"Hey, I said 30!". True, but this type of string needs a terminating ' 0' to say where the it stops. Thus 29 is the maximum number.