July 20th, 2013, 07:41 AM
Scanning two strings
this is the file I'm trying to read.
when I use this code
41 Niobium Nb 92.91
I get the output
char n[LEN], s;
i = 0;
fscanf(inp, "%d%s", &a, n);
But when I change the fscanf line to,
the output is
fscanf(inp, "%d%s%s%lf", &a, n, s, &w);
what is going on here?
July 20th, 2013, 08:32 AM
First you should always use the width specifier when retrieving strings with the scanf() family of functions to limit the number of characters these functions will try to retrieve to avoid buffer overflows.
Next how is LEN defined? What is it's value?
Next you are overflowing your buffer with your variable s. You need at least three characters for the value you have shown, don't forget the end of string character.
July 20th, 2013, 09:23 AM
1. the problem was the size of the string s.
I forgot to consider the null character.
2. LEN was defined as 20, so there shouldn't have been a problem with that.
3. Thanks for the advice. I was told the same thing before here, but I keep forgetting the overflow-prevention measure.