livelive96
livelive96

Reputation: 43

Input a sentence into C++

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

Answers (3)

anonmess
anonmess

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

Arafat
Arafat

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

Ivan Salo
Ivan Salo

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

Related Questions