Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Basic input output (C++)


ghost's Avatar
0 0

Hey I am having a bit of trouble with some C++ input. I have a string which will store an address, however when it encounters a space in the input it will randomize the rest of the inputs. So say we have a string

string adrs;
cout << "Input your ADDRESS: ";
cin >> adrs;
cout << "Your address is: " << adrs << endl;

If the string adrs becomes markup444 penny lane then the spaces would make the script not function, and crash. How can I handle the input of spaces?

Well night, have a good one guys.


ghost's Avatar
0 0

I would have preferred using gets…quite easy to use and you don't even have to change it if you want to convert your program to C. You will have to include another header file(stdio.h) syntax: gets(stringname);

Gets can get the spaces too. another good function in here is puts(stringname);

it automatically adds a newline at the end.Of course if u want to stick with iostream.h…

cin.getline(stringname,no.ofcharecters);


ynori7's Avatar
Future Emperor of Earth
0 0

onejerlo wrote: I would have preferred using gets…quite easy to use Never use gets(). It's not a safe function. It's easy for someone to exploit with a buffer overflow. I have a simple example in the code bank in C. http://www.hellboundhackers.org/code/buffer-overflow-1217_.html

EDIT: If you want to go with stdio, use scanf().


ghost's Avatar
0 0

Yeah…good point..my bad..but scanf cant input spaces directly either…

@chronicburst I guess u can use cin.getline(stringname,no.ofcharecters)…… or u can code up your own header file and make a function of your own and use it.(dont know if that comes under basic or not)


ynori7's Avatar
Future Emperor of Earth
0 0

onejerlo wrote: but scanf cant input spaces directly either…

True. If you need spaces, you can use fgets(). That's a buffer safe version of gets().


ghost's Avatar
0 0

Awesome, cin.getline () is working great. Thank you for the numerous replies.