I have a C program that reads in a list of values separated by commas from a .txt file and assigns the values to variables. I want to assign the first value to a string, the second to an int, the third to a double and the fourth to a double. However, the entire line gets assigned to the string, and the rest are garbage or random values. I want to be able to "skip over" the commas and read assign values between the commas. The final double has a percentage sign at the end so I read the value using a %%, at least thats what I believe should be done.
fscanf(text_file, "%s,%d,%lf,%lf%%%[^\n]", title, &count, &size, &percentage);
A data point would look like this: yellow-leaves,43,4.50,9.00% But the values of title contain the entire line, and the rest of the values are just random garbage values.
Bear in mind that scanf()
is ill-suited for user-input.
Anyway ... "%s"
reads commas (it skips whitespace), try "%[^,]"
.
// assuming
// char title[99];
if (fscanf(f, " %98[^,],%d...", title, ...) != 4) /* error */;
// ^ skip whitespace
Better yet: read a whole line with fgets()
then parse it, possibly with sscanf()
.
char buff[999];
while (fgets(buff, sizeof buff, f)) {
// parse buff
}
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.