将句子输入C ++

liv*_*e96 1 c++ arrays string input char

如何获得包括空格在内的用户输入。

我尝试这样做:

printf("Enter a sentance: ");
scanf("%s", st);
    getchar();
printf("%s", st);
Run Code Online (Sandbox Code Playgroud)

但是当我输入Hello World时,它只会返回Hello

小智 6

scanf只读取到第一个空格,就像cin >> someString. 假设您可以使用<iostream>and <string>,您想要的是

std::string str;
std::getline(std::cin, str);
Run Code Online (Sandbox Code Playgroud)

这将获取所有输入,直到用户按 Enter (\n)。


Iva*_*alo 5

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);
Run Code Online (Sandbox Code Playgroud)