'Strings in a CSV file to initialize a struct
Given a struct:
struct Info {
char name[70];
char address[120];
char email[100];
} info[100];
How would you transfer a .csv file into this structure?
EXAMPLE
Take this .csv file
name,address,email
Carl March,3112 Agriculture Lane,[email protected]
Annie Scrims,1773 Sycamore Lake Road,[email protected]
How would you transfer all of this into the info structure? The white spaces are causing an issue and using a for loop seems way too clunky.
Solution 1:[1]
Instead of using scanf("%s,%s,%s", ...) you should use %[^,\n].
Here is an example:
#include <stdio.h>
struct Info {
char name[70];
char address[120];
char email[100];
} info[100];
int main() {
char buf[1024], eol[2];
int i = 0;
while (i < 100 && fgets(buf, sizeof buf, stdin)) {
if (sscanf(buf, "%69[^,\n],%119[^,\n],%99[^,\n]%1[\n]",
info[i].name, info[i].address, info[i].email, eol) == 4) {
i++;
} else {
printf("invalid record: %s", buf);
}
}
printf("%d records parsed\n", i);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
