[英]How to print two strings on the same line in c
我想输入一个带空格的字符串,并在同一行上打印另一个字符串。
int i = 4;
double d = 4.0;
char s[] = "Apple ";
int x;
double y;
char z[105];
scanf("%d",&x);
scanf("%lf",&y);
scanf("%[^105\n]s",z);
printf("%d\n",i+x);
printf("%0.1lf\n",d+y);
printf("%s %s",s,z);
return 0;
scanf
格式说明符 "%[^105]s"
使用一个字符类 [...]
,它本身就是一个独立的说明符,最后不需要's'
。 通过在末尾放置's'
,您强制scanf
在无限数量的字符之后查找文字's'
,不包括1, 0, 5
。
您似乎打算使用该数字来保护您的数组边界 - 这是一件好事,但在这种情况下正确的格式是"%104[^\\n]"
,它将读取多达104
不包含a的字符'\\n'
(保留空字符的空间)。
例如:
if (scanf("%104[^\n]",z) == 1)
printf("%s %s\n",s,z);
( 注意:始终通过至少检查返回来验证所有用户输入)
另请注意:通过NOT读取上面的'\\n'
,它会在您的输入缓冲区( stdin
)中保留未读状态,如果您的下一次尝试输入是"%c"
或"%[...]"
,您将获取'\\n'
作为输入的一部分,因为nether "%c"
或“%[...]”消耗了前导空格。
将它放在一个示例中,您可以这样做:
#include <stdio.h>
int main (void) {
char s[] = "Apple";
char z[105];
printf ("enter z: ");
if (scanf("%104[^\n]",z) == 1)
printf("%s %s\n",s,z);
else
fputs ("error: stream error or user canceled.\n", stderr);
return 0;
}
( 注意:建议使用fgets()
而不是scanf
来读取行,然后只需修剪填充缓冲区中包含的'\\n'
)
示例使用/输出
$ ./bin/oneline
enter z: is a fruit
Apple is a fruit
使用fgets()
代替
不使用scanf
作为行输入,而是使用面向行的输入函数,如fgets()
,这将消耗整行(包括行结尾)。 确保您的输入缓冲区保持一致状态,不依赖于先前的格式说明符用户,例如
...
#include <string.h>
...
printf ("enter z: ");
if (fgets (z, sizeof z, stdin) != NULL) {
z[strcspn (z, "\n")] = 0; /* trim '\n' from end of z */
printf("%s %s\n",s,z);
}
在评论中编辑每个问题
您的新代码出现问题是 scanf("%lf",&y);
将stdin
的'\\n'
留下未读 ,然后尝试读取scanf("%[^105\\n]",z);
因为你已经排除了在倒置字符类中读取'\\n'
而没有读取任何内容,然后你将stdin
作为输入读取,其中第一个字符是'\\n'
。 "%[^105\\n]"
是指:读取的字符的数量不受限制,并仅当一个停止读出的1, 0, 5
或'\\n'
字符(或EOF
遇到)。
由于stdin
剩下的内容,以及如何处理前导空格取决于所使用的格式说明 符 ,因此使用scanf
混合输入充满了新C程序员的陷阱 。 这就是建议用户输入fgets()
(或POSIX getline()
),然后使用sscanf
从填充缓冲区解析所需信息的原因。 使用面向行的输入函数,在每个输入上完全消耗该行(给定足够的缓冲区大小 - 不要吝啬),消除了scanf
的问题。
要使当前代码正常工作,您可以:
#include <stdio.h>
/* simple function to empty remainder of line in stdin */
void empty_stdin (void)
{
int c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
}
int main (void) {
int i = 4, x;
double d = 4.0, y;
char s[] = "Apple ", z[105];
scanf("%d",&x);
scanf("%lf",&y); /* leaves '\n' as next char in stdin */
empty_stdin(); /* empty extraneous characters */
scanf("%104[^\n]",z); /* read up to 104 chars, \n, or EOF */
printf("%d\n",i+x);
printf("%0.1lf\n",d+y);
printf("%s %s\n",s,z);
return 0;
}
( 验证每次调用scanf
- 留给你)
如果您有其他问题,请与我们联系。
我在scanf中使用\\ n解决了这个问题( “%lf \\ n ”,&y);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.