I have a file with contents as shown below.
[John][Antony][Mathew] Australia
I need to use fscanf
to read contents from file.
Output should be:
firstName = John
middleName = Antony
lastName = Mathew
Country = Australia
What is the format to be used in fscanf
to get firstName, middleName, lastName and country in separate strings?
Currently fscanf(fp, "[%[^]]",firstName)
gives firstName correctly.
Akin to @BLUEPIXY comment "[%[^]]][%[^]]][%[^]]] %[^\\n]%*c"
.
Since data is certainly per line , read a line first and then parse it.
The format needed is "[%99[^]]]"
which says to 1) scan '['
2) scan up to 99 non- ]
char and form a string 3) scan ']'
.
#define N 100
#define FMT "[%99[^]]]"
#define FMTCTY " %99[^\n]"
char firstName[N], middleName[N], lastName[N], Country[N];
char buf[4*N + 10];
while (fgets(buf, sizeof buf, fp) != NULL) {
if (4 != sscanf(buf, FMT FMT FMT FMTCTY, firstName, middleName, lastName, Country)) {
break;
}
foo(firstName, middleName, lastName, Country);
}
Confident OP can form the needed output format string.
char buf[1024];
FILE* fp = fopen("file.in", "r");
fgets(buf, sizeof(buf), fp);
fclose(fp);
// substitute '[' and ']' with a space
sscanf(buf, "%s%s%s%s", firstName, middleName, lastName, Country);
Also can be done by reading character stream and overpass all spaces, '[' and ']'.
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.