Reputation: 43
How can I get user input including spaces.
I tried doing this:
printf("Enter a sentance: ");
scanf("%s", st);
getchar();
printf("%s", st);
But when I enter Hello World it only returns Hello
Upvotes: 0
Views: 2015
Reputation: 495
scanf
only reads up until the first space, as does cin >> someString
. What you want, assuming you can use <iostream>
and <string>
, is
std::string str;
std::getline(std::cin, str);
This will get all input up until the user hits enter (\n).
Upvotes: 5
Reputation: 368
Try like this:
#include <iostream>
#include <string>
int main() {
std::string st;
std::cout << "Enter a sentence: ";
getline(std::cin, st);
std::cout<< st;
}
Upvotes: 1
Reputation: 821
Use fgets() (which has buffer overflow protection) to get your input into a string.
printf("Enter a sentance: ");
fgets(st, 256, stdin);
printf("%s", st);
Upvotes: 5