繁体   English   中英

C-如何输入这行

[英]C - how to input this line

我试图将这种行“ 1 Myke Tyson 1234567891”作为结构的输入

做这个的最好方式是什么?

这是我尝试的:

scanf("%d", &list.n1);
fgets(list.name, 14, stdin);

for(i = 0; i < 10; i++)
{
    scanf("%d", &list.n2[i]);
}

编辑:这是结构:

   struct ex{
         int n1;
         char name[14];
         int n2[10];
   }

使用fgets()sscanf()和其他代码进行解析。

如果字段中不允许使用分隔符(空格),则此解析将更加健壮。 .name或多个潜在空间使解析复杂化。 推荐用逗号分隔的字段。 此外, int n2[10]字段不常见。 为什么不给unsigned long long n2

确保检查fgets()sscanf()

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

typedef struct ex {
  int n1;
  char name[14];
  int n2[10];
} ex;

int ReadEx(ex *dest) {
  char buf[20 + 1 + 14 - 1 + 1 + 10 + 2];  // Or use something big like buf[100]
  if (fgets(buf, sizeof buf, stdin) == NULL ) {
    return -1;  // EOF or I/O Error
  }

  char name[14 + 1]; // temp place for name and final space separator
  int p1, p2;        // Offset for beginning and end of n2 array
  unsigned long long ull;  // Dummy to save n2 array
  if (3 != sscanf(buf, "%d %14[A-Za-z ]%n%llu%n", 
      &dest->n1, name, &p1, &ull, &p2)) {
    return 1; // format error
  }

  // strlen(name) cannot have the value of 0 here as sscanf() is 3
  size_t SpaceIndex = strlen(name) - 1;
  if ((name[SpaceIndex] != ' ') || ((p2 - p1) != 10)) {
    return 1; // format error, space expected at end of name and 10 digits
  }
  // name cannot contain only spaces due to the space before %14
  while (name[SpaceIndex] == ' ') {
    name[SpaceIndex--] = '\0';
  }
  strcpy(dest->name, name);
  int i;
  for (i = 0; i < 10; i++) {
    dest->n2[i] = buf[p1 + i] - '0';
  }
  return 0;
  // One could use the below approach but it is not so extensible.
  // if (12 != sscanf(buf, "%d %14[A-Za-z ]%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d %c",
  //   &dest->n1, name, &dest->n2[0], &dest->n2[1], ... &dest->n2[9], &dummychar)) {
}

一种可能的方法是

struct ex{
     int n1;
     char name[14];
     char n2[11];
}

scanf("%d", &list.n1);
fgets(list.name, 14, stdin);
fgets(list.n2, 11, stdin);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM