Reputation: 6549
I'm trying to search a text file using C for a string of characters that will always be in a specific place. Specifically I'm looking for three sequential dashes. When it finds the three dashes it should return the line on which it was found. It should then continue to the next line and continue searching for the three sequential dashes until it reaches the end of the file. Each time is should print the line number.
This is what I have so far:
int main() {
FILE *f;
char inName[80];
printf("Read text from: ");
scanf(" %79[^\n]s\n", inName);
f = fopen(inName, "r");
if (f == 0) printf("ERROR: Cannot open file %s for reading.\n", inName);
int lineNumber = 0;
for(;;) {
char line[127];
fgets(line, 127, f);
if (!feof(f)) {
lineNumber++;
} else {
break;
}
double lf;
int d, d1;
char s[30];
char s1[4];
sscanf(line, " %d, %s, %s, %s, %s, %d, %d, %lf",
&d, &s, &s, &s, &s, &d, &s1, &lf);
if (s1 == "---") {
printf("%d\n", lineNumber); // what line
}
}
fclose(f);
return(0);
}
This code runs but does not print anything. Could anyone show how to get this done? Thanks :)
Upvotes: 1
Views: 13181
Reputation: 122011
This is not how to compare strings in C:
if (s1 == "---")
as is comparing the address of s1
with the address of the string literal "---"
.
Use strcmp()
:
if (strcmp(s1, "---") == 0)
{
Always check the return value of sscanf()
to ensure the variables have actually been assigned a value before attempting to use them. The ,
comma character is not treated as delimiter when processed with "%s"
format specifier, only whitespace is used as delimiter. To prevent the consumption of the ,
use a scan set, similar to how you have done earlier in the program (note corrections to sscanf()
arguments):
if (sscanf(line,
" %d, %29[^,], %29[^,], %29[^,], %29[^,], %d, %3[^,], %lf",
&d, s, s, s, s, &d, s1, &lf) == 8)
{
}
Upvotes: 5
Reputation: 6226
You cannot compare char[]
with ==
. Use strcmp instead.
if( strcmp(s1, "---") == 0 )
Upvotes: 2
Reputation: 43364
if (s1 == "---")
You're comparing strings the wrong way, you should use strcmp()
follow this example http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1057537653&id=1043284385
Upvotes: 5