我需要一些帮助来解决我遇到的一些问题。我是 C 语言新手,我需要帮助尝试读取中间带有分隔符的数据字符串并将它们保存到结构中。我怎样才能做到这一点?
字符串的格式如下,格式为 A:B:C:D:E
示例
0002:0001:0001:0042:ASD
0001:0011:0010:0023:DDD
当读取字符串时,它会同时被验证并存储到结构中。
A的值应该在1-100之间
B的值应该在1-100之间
C的值应该在1-10之间
D的值应该在1-50之间
E 的值应在 25 个字符以内。
有人可以指导我如何编写代码吗?如果这听起来很简单,我很抱歉,但我对此真的很陌生。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char ch, file_name[25];
FILE *fp;
char * aline;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(fp) ) != EOF ){
aline=(strtok,":");
while (aline != NULL)
{
printf ("%s\n",aline);
aline = strtok (NULL, " :");
}}
fclose(fp);
return 0;
}
最佳答案
您可以使用 sscanf
或 fscanf
填充结构
sscanf(string, "%d:%d:%d:%d:%26s", &struc->A, &struc->B, &struc->C,
&struc->D, sturc->E);
fscanf(file, "%d:%d:%d:%d:%26s", &struc->A, &struc->B, &struc->C,
&struc->D, sturc->E);
要验证字符串,您可以检查空字符是否被覆盖,只需确保您使用额外的字符声明字符串即可。
if (struc->E[26] != '\0') {
struc->E[26] = '\0';
goto invalid;
}
验证其他字段将是简单的边界检查
if (struc->A < 1 || struc->A > 100) goto invalid;
您还应该注意,scanf
函数并不总是填充每个字段,而是会返回它们填充的字段数。因此,如果您期望不规则的输入,您应该检查它返回的数字。
if (scanf(...) != 5) {
// either populate with default values or invalidate
}
关于c - 读取带有分隔符的数据字符串并存储到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26697294/