2 Replies - 560 Views - Last Post: 05 March 2016 - 10:24 AM Rate Topic: -----

#1 Kurissu   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 19
  • Joined: 28-September 15

Confirming sequence of characters in char array with strstr()

Posted 05 March 2016 - 09:31 AM

Hello!

I've been trying my hand at coding in C to remove myself from the syntatic sugar of higher level languages. Inevitably I have encountered a brick wall on what would seem like a trivial task in a high level language, by trying to confirm if a sequence of characters is within an array of characters.

# include <stdio.h>
# include <string.h>

int main(int argc, char* argv[])
{
	FILE* file = fopen("test.txt", "r");
	char line[256];
	char *characters = "learning";

	while (fgets(line, sizeof(line), file))
	{	
		if (strchr(characters, *line));
			{
				printf("found\n");
			}
		
		printf("%s", line);
	}

	fclose(file);
	return 0;
}



Output
found
Hi my name is Chris
found
I am currently learning the C programming language
found
I am currently in a pickle



The program is supposed to get one line from the text file at a time and check whether the sought after string is within it. And the current condition evaluates true for every line. And in the case of the sample text, the string "learning" can only be found on one of the lines. For the sake of testing: I tried to use a completely different string to search for, one that doesn't appear on any of the lines. And I get the same output as above.

I'd appreciate it if someone could provide me with insight that could lead me to a solution.

Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Confirming sequence of characters in char array with strstr()

#2 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7915
  • View blog
  • Posts: 26,425
  • Joined: 05-May 12

Re: Confirming sequence of characters in char array with strstr()

Posted 05 March 2016 - 10:14 AM

Look closely at your line 12. In particular, look at the end of the line 12.
Was This Post Helpful? 0
  • +
  • -

#3 kaa   User is offline

  • D.I.C Addict

Reputation: 225
  • View blog
  • Posts: 805
  • Joined: 15-April 11

Re: Confirming sequence of characters in char array with strstr()

Posted 05 March 2016 - 10:24 AM

... and strchr only looks for the first occurrence of a character in a string, so here it's looking for 'H', then 'I', and then 'I' again, in the string "learning".
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1