gpt4 book ai didi

c - C中如何使用scanf同时扫描double和char到double数组中

转载 作者:行者123 更新时间:2023-11-30 16:59:17 28 4
gpt4 key购买 nike

我有一个项目要做,要求我根据用户的输入将两个 vector 的地址记录到一个 double 组中。然而。例如,如果用户写

3  
1 2 3
3 4 5

这意味着 vector 是3维的,并且两个 vector 是(1,2,3)(3,4,5)。如果用户写入,

2  
1 2
2 3

这意味着 vector 是二维的,并且两个 vector 是(1,2)(2,3)。我需要将这两个 vector 的坐标记录到两个 double 组x和y中。如何使用 scanf 将坐标读入这两个数组? (我不知道用户是否以正确的格式书写,他们有可能在应该只写数字的地方写字母或其他符号。如果他们写数字以外的字符,我需要返回 - 1.)

到目前为止我的代码是

double x[100];  
char c;
c = getchar();
do {
scanf("%lf",x)}
while (c!= '\n');

最佳答案

据我了解您的问题,这里有一个应该可以解决它的代码。

#include <stdio.h>
#include <stdlib.h>
#define NB_VECTORS 2 //Increase if you have more than 2 vectors

int* readVector(int size) {
// Allocation fits the size
int* vector = malloc(size*sizeof(int));
//While the vector are the same size it works
for (int i = 0; i < size; i++)
if (scanf("%d", vector+i) != 1)
return null; //bad input
return vector;
}

int main(int argc, char** argv) {
int size;
scanf("%d", &size);

//Each line is vectorized inside vectors[i]
int* vectors[NB_VECTORS];#
for (int i = 0; i < NB_VECTORS; i++)
vectors[i] = readVector(size);

return 0;
}

[编辑]返回已填充的项目数 -> cf http://www.cplusplus.com/reference/cstdio/scanf/

关于c - C中如何使用scanf同时扫描double和char到double数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38268389/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com