简体   繁体   中英

scanf for numbers separated by space

I know the amount of numbers separated by space. The following code does work int Windows, but does not in Linux.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
    ios_base::sync_with_stdio(0);
    unsigned long k,p,q, all;


    cin >> k >> p >> q; 
    vector<long> klo(k);
    all = 0;
    for(unsigned long i = 0;i<k;i++){   
        scanf("%d", &klo[i]);
        all += klo[i];
    }
}

As I said, works perfectly under Windows, but Linux assign there some random values: -1220155675-1220155675-12201556750

What's wrong?

Maybe the word bit size is different between platforms, you have long type in your vector and you are reading only int type, which could not rewrite the whole size of the long variable and you'll get a long variable with half its bytes uninitialized.

Try to change:

scanf("%d", &klo[i]);

Into:

scanf("%ld", &klo[i]);

ld denotes long decimal type.

%d is for reading int. You are trying to read a long - that would be %ld .

One of the advantages of the C++ IO system is that cin >> klo[i] would do the right thing for both types.

When I compiled your code on Linux, it gave me the following error:

$: /tmp$ g++ -g foobar.c
foobar.c: In function ‘int main(int, char**)’:
foobar.c:17:28: warning: format ‘%d’ expects argument of type ‘int*’, but argument 2 has type ‘long int*’ [-Wformat=]
         scanf("%d", &klo[i]);
                            ^

I changed it to scanf ( "%ld", &klo[i] ); and it worked. Windows is tolerant. I also had to add

#include <stdio.h>

as an additional include file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM