【发布时间】:2016-08-30 12:24:45
【问题描述】:
在 Hackerrank 上越来越熟悉 C(++) 时遇到问题。使用 scanf() 我想读取具有一堆不同值的行。
问题是 char 之后的值被忽略了。阅读解决方案是在字符之前添加一个空格,但我尝试在每个值的单独行上运行 scanf(),并且只保留字符前面的空格,但问题仍然存在。
要吸取的教训似乎是使用 scanf() 而不是任何其他类型的输入法。所以不能用 cin 或 fscanf() 读取。这样做的原因是可以在同一行读取各种值。因此,我也不想为读取输入制作超过这一行的内容。
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int i;
long l;
long long ll;
char c;
float f;
double d;
/** Read "3 444 12345678912345 a 334.23 14049.30493" from stdin */
scanf("%i %ld %lld %c %f %lf", &i, &l, &ll, &c, &f, &d);
printf("%d\n", i); // 3, as expected
printf("%ld\n", l); // 444 also as expected
printf("%lld\n", ll); // 12345678912345 ...
printf("%c\n", c); // 'a'
printf("%f\n", d); // 14049.30493 ?? It should be: 334.23
printf("%lf\n", d); // 14049.30493 but this time as it should be.
return 0;
}
【问题讨论】:
标签: scanf