簡體   English   中英

如何使用scanf將double和char同時掃描到C中的double數組中

[英]how to use scanf to scan double and char at the same time into a double array in C

我有一個項目要做,要求我根據用戶的輸入將兩個向量的地址記錄到雙精度數組中。 然而。 例如,如果用戶寫

 3 1 2 3 3 4 5 

這意味着向量是3維的,兩個向量是(1,2,3)(3,4,5) 如果用戶寫,

 2 1 2 2 3 

這意味着向量是二維的,兩個向量是(1,2)(2,3) 我需要將這兩個向量的坐標記錄為兩個雙精度數組x和y。 如何使用scanf將坐標讀取到這兩個數組中? (我不知道用戶是否以正確的格式書寫,他們有可能在他們應該只寫數字的地方寫字母或其他符號。如果他們寫的不是數字,我需要返回字符- 1.)

到目前為止,我的代碼是

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

scanf對於解析用戶輸入不是一個很好的功能。 它接受2.1sdsa2作為值為2.1的浮點數,並且接受2.1sdsa2作為值為2的int值。 僅當您知道輸入有效時才應使用scanf

如果需要使用scanf ,則可以掃描到一個字符串中,然后編寫自己的語法分析以檢查輸入是否有效。

一個簡單的例子:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char s[10];
  while (1 == scanf("%s", s))
  {
     printf("%s\n", s);
     if (strcmp(s, "s") == 0) break;
  }
  return(0);
}

程序繼續直到輸入為s

輸出示例:

1 2.0 2.6
1
2.0
2.6
2a 4567 2.a23
2a
4567
2.a23
s
s

請注意, scanf在看到空格時會返回。 因此輸入1 2 3將是3個循環(返回3個子字符串)。

因此,您不僅可以打印,還可以將解析器放入while

  while (1 == scanf("%s", s))
  {
      // Parse the string s and add value to array
  }

據我了解您的問題,以下是應該解決的代碼。

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

[EDIT]返回已填寫的項目數-> cf http://www.cplusplus.com/reference/cstdio/scanf/

也許您只需要這樣的東西(簡單,最少,沒有錯誤檢查的示例):

int main()
{
  int x[3], y[3];

  int dimension;
  scanf("%d", &dimension);

  if (dimension == 3)
  {
    scanf("%d %d %d", &x[0], &x[1], &x[2]);
    scanf("%d %d %d", &y[0], &y[1], &y[2]);
  }
  else if (dimension == 2)
  {
    scanf("%d %d", &x[0], &x[1]);
    scanf("%d %d", &y[0], &y[1]);
  }

  ...
  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM