我试图用C ++编写代码来刷新我的记忆,并且无法弄清楚为什么以后没有工作:
我应该从scanf读入以下值:
3 444 12345678912345 a 334.23 14049.30493
然后将它们打印到各自的行。像这样:
3
444
12345678912345
a
334.23
14049.30493
我使用的代码是:
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int inum;
long lnum;
long long llnum;
char ch;
float fnum;
double dfnum;
scanf("%d%ld%lld%c%f%lf", &inum, &lnum, &llnum, &ch, &fnum, &dfnum);
printf("%d\n%ld\n%lld\n%c\n%f\n%lf", inum, lnum, llnum, ch, fnum, dfnum);
return 0;
}
但由此产生的输出是:
3
444
12345678912345
0.000000
0.000000
我在这里做错了什么?
答案 0 :(得分:4)
using namespace std
。scanf
。fscanf
手册页,尤其是%c
修饰符。fprintf
手册页,因为其修饰符与fscanf
修饰符不同。答案 1 :(得分:3)
尝试在scanf()
格式字符串中添加空格以帮助scanf()
:
scanf("%d %ld %lld %c %f %lf", &inum, &lnum, &llnum, &ch, &fnum, &dfnum);
scanf()
返回它实际读取的值的数量,例如:
if (scanf("%d %ld %lld %c %f %lf", &inum, &lnum, &llnum, &ch, &fnum, &dfnum) == 6)
printf("%d\n%ld\n%lld\n%c\n%f\n%lf", inum, lnum, llnum, ch, fnum, dfnum);
话虽如此,您将问题标记为C ++,但您显示的代码主要是C而不使用任何C ++功能(您的using
语句不计算,因为您实际上并未使用{ {1}}命名空间)。你在尝试的东西在C ++中会更像这样:
std
可替换地:
#include <iostream>
using namespace std;
int main() {
int inum;
long lnum;
long long llnum;
char ch;
float fnum;
double dfnum;
if (cin >> inum >> lnum >> llnum >> ch >> fnum >> dfnum)
cout << inum << "\n" << lnum << "\n" << llnum << "\n" << ch << "\n" << fnum << "\n" << dfnum;
return 0;
}