我知道按空格分隔的数字量。以下代码适用于Windows,但不适用于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];
}
}
正如我所说,在Windows下完美运行,但Linux为其分配了一些随机值:-1220155675-1220155675-12201556750
出了什么问题?
答案 0 :(得分:4)
也许平台之间的位大小不同,你的向量中有很长的类型而你只读int
类型,它不能重写长变量的整个大小而你会得到一个长的变量,其半个字节未初始化。
尝试改变:
scanf("%d", &klo[i]);
分为:
scanf("%ld", &klo[i]);
ld
表示长十进制类型。
答案 1 :(得分:3)
%d
用于读取int。你想读长篇大论 - 那就是%ld
。
C ++ IO系统的一个优点是cin >> klo[i]
可以为这两种类型做正确的事。
答案 2 :(得分:3)
当我在Linux上编译你的代码时,它给了我以下错误:
$: /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]);
^
我将其更改为scanf ( "%ld", &klo[i] );
并且有效。 Windows很宽容。我还必须添加
#include <stdio.h>
作为附加的包含文件。