【发布时间】:2016-08-19 17:32:23
【问题描述】:
这个问题来自 HackerRank,我尝试用 %[^\n]s 表示一个长词。但是,输出继续产生.0
如何将 %[^\n]s 替换为其他字符串以接收输入?
这是输入:
12
4.0
is the best place to learn and practice coding!
这是我的输出:
16
8.0
HackerRank .0
这是预期的输出:
16
8.0
HackerRank is the best place to learn and practice coding!
这是我的完整代码,如您所见,它无法识别 %[^\n]s。如何解决这个问题呢?谢谢你。
完整代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";
// Declare second niteger, double, and String variables.
int value1, sum1, value2;
double e = 2.0, sum2;
char t[30];
// Read and save an integer, double, and String to your variables.
scanf(" %d", &value1);
scanf("%d", &value2);
scanf("%[^\n]s", t); //** POINT OF INTEREST **
// Print the sum of both integer variables on a new line.
sum1 = value1 + i;
printf("%d\n", sum1);
// Print the sum of the double variables on a new line.
sum2 = d * e;
printf("%.1lf\n", sum2);
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
printf("%s %s", s, t);
return 0;
}
【问题讨论】:
-
请澄清您的问题。检查How to Ask。
-
如何将 %[^\n]s 替换为其他字符串以接收输入?
-
流中可能有一个换行符,从您读取的最后一个数字开始。这会导致
%[^\n]失败,因为在下一个换行符之前没有要读取的字符。另外,%[]之后不需要s。 -
我没有投反对票,但这里有一个提示。发布代码时,只需将其粘贴到您的问题中,缩进 4 个或更多空格。该网站会将其视为代码,并且每个人都可以更轻松地阅读。
-
使用
scanf盲目地将任意长度的用户输入读取到固定大小的缓冲区中只是在乞求缓冲区溢出。fgets可能就是你要找的:stackoverflow.com/questions/1252132/…