将一串输入存储到 C 中的结构中

Storing a string of inputs into a struct in C

想知道如何以 "string,character,integer,integer" 格式存储用户输入的字符串 进入一个结构。 例如将 "apple,c,5,10" 存储到

typedef struct {
char item[80];
char letter;
int x,y;
}information;

information apple;

我试图避免使用 scanf 和一长段代码将逗号变成定界符,所以想知道是否有任何其他方法可以快速读取 scanf 并将此信息放入结构中

您可以在 scanf() 的格式字符串中使用多个格式说明符以 一次扫描所有输入 ,通过 逗号分隔 用户输入,喜欢

int ret = -1;
if ((ret = scanf("%79[^,],%c,%d,%d", apple.item, &apple.letter, &apple.x, &apple.y)) != 4)
                       //always check the return value of scanf()                       
{
   printf("scanf() failed\n");
   //do something to avoid usage of the member variables of "apple"
} 

不过,我会推荐long way,喜欢

  • 使用 fgets()
  • 读取行
  • 使用 strtok(), 作为分隔符进行分词
  • 使用令牌(或根据需要使用 strtol() 进行转换)。

非常安全和稳健。

您可以使用 scanf 指定复杂的格式,例如:

scanf("%79[^,],%c,%d,%d", apple.item, &apple.letter, &apple.x, &apple.y);

%79[^,] 表示扫描任何非逗号字符,最多 79 个字符。

请注意,如果用户输入格式不正确的字符串(如 "aaa;b;1;2"),这不会进行错误处理。为此,您需要编写更多代码。参见 strtok

尝试使用函数 read() 读取,然后使用 strtok()

拆分字符串

这里有一些参考资料:

strtok : http://man7.org/linux/man-pages/man3/strtok.3.html

阅读:http://linux.die.net/man/2/read