int*vector只接受第一个给定值

int*vector只接受第一个给定值,c,vector,struct,C,Vector,Struct,我在用C编写的代码中遇到了一些问题。这都是关于一个int*向量的初始声明和动态分配,但是当用数据填充它时,它会卡在第一个元素上,并且不会增加计数器来填充向量的其余部分 我的头文件:instance.h struct pbCoupe { int tailleBarre; int nbTaillesDem; int nbTotPcs; int * taille; int * nbDem; }; 我的代码:coupe.c pb->taille = (int*)

我在用C编写的代码中遇到了一些问题。这都是关于一个int*向量的初始声明和动态分配,但是当用数据填充它时,它会卡在第一个元素上,并且不会增加计数器来填充向量的其余部分

我的头文件:instance.h

struct pbCoupe
{
   int tailleBarre; 
   int nbTaillesDem; 
   int nbTotPcs;
   int * taille; 
int * nbDem; 
};
我的代码:coupe.c

pb->taille = (int*) malloc (pb->nbTaillesDem * sizeof(int)); 
pb->nbDem = (int*) malloc (pb->nbTaillesDem * sizeof(int));


while (i < pb->nbTaillesDem)
{
    fscanf_s(instanceFile,"%s",data,sizeof(data)); 
    pb->taille[i] = atoi(data); //<-- here is the problem !! it only accept the first value and ignore all the rest 

    printf("%s\n",data);

    fscanf_s(instanceFile,"%s",data,sizeof(data)); 
    pb->nbDem[i] = atoi(data); //<-- the same problem here too !!
    printf("%s\n",data);

    i++;
}
pb->taille=(int*)malloc(pb->nbTaillesDem*sizeof(int));
pb->nbDem=(int*)malloc(pb->nbTaillesDem*sizeof(int));
而(inbTaillesDem)
{
fscanf_s(instanceFile,“%s”,数据,大小f(数据));

pb->taille[i]=atoi(data);//nbDem[i]=atoi(data);//您对
sizeof
的解释是错误的,因为
data
是字符串解析到的缓冲区

它返回变量的大小,而不是变量(或指针)指向的大小

C中的字符串都是指向大小的指针,在32位系统中为4字节,在64位系统中为8字节

由于它打印所有的数字,并读取每个循环迭代4字节=4个字符所需的更多数字,因此atoi on解析第一个整数并返回

编辑:如果是缓冲区数组,
sizeof
返回数组的大小

为了解决这个问题,您需要确保每次循环迭代只读取一个数字

如果您不喜欢文字字符串,最好使用:

fscanf(instanceFile, "%d", ((pb->taille) + i))); //and store the integer into the index right away //last param same as &pb->taille[i] fscanf(instanceFile,“%d”,((pb->taille)+i)); //并立即将整数存储到索引中 //最后一个参数与&pb->taille[i]相同
请给出所有输入和输出,特别是添加缺少的变量类型,并告诉您希望发生什么。请在“instanceFile”中显示数据。问题可能是使用fscanf_.pb->nbtailledem从instanceFile中读取字符串。pb->nbtailledem是文本文件中的元素数!我将逐行读取pb->taille和pb->nbDem的组合。这段代码应该给我两个向量,填充int6500//pb->tailleBarre 8//pb->nbtailledem 52//pb->nbTotPcs 350 6//pb->taille&pb->nbDem520 7//在1230 5 500 7 630 10 4200 4 2500 9 660 4结束之前,其余部分都是一样的,但是从文件中读取时没有问题,因为每次我打印“数据”时都没问题!但是我们不知道数据是如何声明的……它可能是char data[128];例如,在这种情况下,sizeof(data)是128。但是,如果数据是这样声明的:char*data;char data[10];这是数据的声明。正如Brad所说,每次迭代您要读取10个字节(或文件中的10个字符)。您需要将读取限制为每次迭代整数字符串后的第一个空格/空字符是,或字符串结尾