I'm trying to take as input of a struct this kind of line "1 Myke Tyson 1234567891"
What is the best way to do this?
This is what I tried:
scanf("%d", &list.n1);
fgets(list.name, 14, stdin);
for(i = 0; i < 10; i++)
{
scanf("%d", &list.n2[i]);
}
EDIT: This is the struct:
struct ex{
int n1;
char name[14];
int n2[10];
}
Use fgets()
, sscanf()
and additional code to parse.
This parsing would be more robust if the separator (a space) was not allowed in a field. The potential space or spaces within .name
convoluted the parsing. Recommend comma separated fields. Further the int n2[10]
field is unusual. Why not unsigned long long n2
?
Be sure to check result of 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)) {
}
One of the possible way is
struct ex{
int n1;
char name[14];
char n2[11];
}
scanf("%d", &list.n1);
fgets(list.name, 14, stdin);
fgets(list.n2, 11, stdin);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.