C 中扫描包含空格的字符串

发布于 2024-10-04 09:53:21 字数 252 浏览 0 评论 0原文

在我的代码中:

scanf("%s", &text);
printf("%s\n", text);

输入:

hi how are you

输出:

hi

而不是

hi how are you

我能做什么来修复它?

In my code:

scanf("%s", &text);
printf("%s\n", text);

Input:

hi how are you

Output:

hi

and not

hi how are you

what can I do to fix it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

离鸿 2024-10-11 09:53:21

看看 fgets

fgets()函数最多读取一个
小于字符数
由给定流中的 n 指定
并将它们存储在字符串中
s.当出现换行符时停止读取
在文件末尾找到字符或
错误。换行符(如果有)是
保留。如果读取到任何字符
并且没有错误,‘\0’
字符被附加到结束
字符串。

Look at fgets

The fgets() function reads at most one
less than the number of characters
specified by n from the given stream
and stores them in the string
s.Reading stops when a newline
character is found, at end-of-file or
error. The newline, if any, is
retained. If any characters are read
and there is no error, a `\0'
character is appended to end the
string.

悸初 2024-10-11 09:53:21

我想您正在寻找

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

Which will read up to a newline delimiter.或者如果您使用其他分隔符

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);

I suppose you're looking for

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

Which will read up to a newline delimiter. Or if you're using some other delimiter

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
以往的大感动 2024-10-11 09:53:21

使用 fgets 获取您的输入:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    char text[80];
    fgets(text, sizeof(text), stdin);
    printf("%s\n", text);
}

Use fgets to get your input:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    char text[80];
    fgets(text, sizeof(text), stdin);
    printf("%s\n", text);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文