Basic input output (C++)
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.
getline(cin, adrs);
That grabs the whole line rather than just the first word. You could also write it as: cin.getline (adrs ,256); That takes the first 256 characters entered.
http://www.cplusplus.com/reference/iostream/istream/getline.html
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);
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().
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)