读入特定数量的变量

时间:2016-02-05 23:01:41

标签: c printf scanf

我必须阅读不同的坐标并将它们保存到结构中。对于此任务,我只能使用

#include <stdio.h>
#include <stdbool.h>

scanf将其读入。我还必须使用GCC编译器。 对于一个结构,我需要4个坐标,因此插入内容可能如下所示:

Coordinates: 11 12 13 14 21 22 23 24
//           | First   |  | Second |

对于读入,我有以下结构:

int read() {
    int a;
    scanf("%d",&a);
    return a;
}

主:

printf("Coordinates: ");
int buffer = read();
while(buffer != 0) {
    //write current buffer in struct
    ...
    buffer = read();
}

所以问题是,使用这种结构,插入需要以0结束。但我的任务是,当没有更多的“四人组”坐标时,读入程序结束。 例如:

Coordinates: 11 12 13 14 21 22 23 24 31
//            | First  |  | Second |  invalid -> while loop ends

所以我不知道如何取消while循环,因为我不知道用户将输入多少坐标。

允许的库功能:scanf(), printf(), putchar()

我希望你们中的某些人能够理解我并帮助我。

3 个答案:

答案 0 :(得分:0)

OP的代码无法区分读取"0"和遇到错误。它不会跟踪读取4个数字中的多少个。它不会检测前缀"Coordinates:"

int read() {
    int a;
    scanf("%d",&a);
    return a;
}

一次读入“fourpack”,1个fourpack。

struct pt4 {
  int i[4];
};

// Return EOF, 0, 1, or 4
struct pt *Read_foursome(struct pt4 *fourpack, int count) {
  // Look for prefix
  if (count == 0) {
    // Record number of characters read
    int n = 0;
    if (scanf(" Coordinates:%n", &n) == EOF) return EOF;
    if (n == 0) return 1; // Unexpected data, prefix not exactly there.
  }
  // record the number of fields successful scanned.
  int n = scanf("%d%d%d%d", 
      &fourpack.i[0], &fourpack.i[1], &fourpack.i[2], &fourpack.i[3]);

  // No more data
  if (n == EOF) return EOF;  

  // no numeric  data
  if (n == 0) return 0;

  // Unexpected data
  if (n != 4) return 1;

  // As expected
  return 4;
}

样本用法

int n;
int count = 0;  
struct pt4 fourpack;
printf("Coordinates:"); 
while ((n = Read_foursome(&fourpack, count)) == 4) {
  // Use fourpack
  printf(" %d %d %d %d", 
      fourpack.i[0], fourpack.i[1], fourpack.i[2], fourpack.i[3]);
  count++;
}
printf("\n"); 

// If n == 0 maybe time to look for another line of fourpack
// If n == 1, some syntax error in the line.

答案 1 :(得分:-1)

检查scanf的返回值。它返回它读取的项目数。如果它返回1,则它读取整数。如果它返回0则它没有(由于文件结束或输入错误)。

int read() {
    int a;
    if (scanf("%d",&a) < 1) {
        return 0;
    }
    return a;
}

请注意,使用此功能无法区分EOF和用户键入0。两者都会导致read()返回0.如果0是合法的输入值,那么您应该采用另一种方式向调用者指示错误。

答案 2 :(得分:-2)

如果你遵循这个伪代码,它应该工作:

  1. 获取用户的所有输入,直到您不想输入更多输入(无论情况如何)并存储在int数组中。
  2. 以4的倍数(使用mod)遍历数组,如果你有4的倍数将它存储在结构中。
  3. 如果不是4的倍数,这意味着您已经耗尽了数组,并且没有更多的“四人组”坐标。
  4. 所以基本上你会有两个while循环(更简单)。一个循环只会将数字存储在一个数组中,直到您不想输入更多输入(无论情况如何)。而另一个while循环将以4的倍数通过数组。