hax0r_n_code hax0r_n_code - 26 days ago 14
C++ Question

New to C++ and scanf is not properly reading/printing input

I'm trying to refresh my memory in writing code using C++ and can't figure out why the follow isn't working:

I'm supposed to read in from scanf the following values:

3 444 12345678912345 a 334.23 14049.30493


And then print them each to their own line. Like so:

3
444
12345678912345
a
334.23
14049.30493


The code I'm using is this:

#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;
}


But the output produced by this is:

3
444
12345678912345

0.000000
0.000000


What am I doing wrong here?

Answer

Try including spaces in your scanf() format string to help scanf():

scanf("%d %ld %lld %c %f %lf", &inum, &lnum, &llnum, &ch, &fnum, &dfnum);

scanf() returns the number of value it actually read, eg:

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);

That being said, you tagged your question as C++, but the code you showed is mostly C and not using any C++ functionality (your using statement doesn't count since you are not actually using anything from the std namespace). What you are attempting would look more like this in C++:

#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;
}

Alternatively:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    string line;

    int inum;
    long lnum;
    long long llnum;
    char ch;
    float fnum;
    double dfnum;

    if (getline(cin, line))
    {
        istringstream iss(line);
        if (iss >> inum >> lnum >> llnum >> ch >> fnum >> dfnum)
            cout << inum << "\n" << lnum << "\n" << llnum << "\n" << ch << "\n" << fnum << "\n" << dfnum;
    }

    return 0;
}
Comments