Jump to content

find a string

- - - - -

  • Please log in to reply
3 replies to this topic

#1
fazla

fazla

    Newbie

  • Members
  • Pip
  • 2 posts
Hi!I'm new to C programming and I wanted to ask where is the error in this code:
I have a file text ( frase.txt),placed in the same folder and I have to search for a string in this text and if I find that string I have to print it.


Code:

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


int main(){
const char searchingString[20];
FILE *fillle= fopen("frase","r");

char *s;
char *token;
printf("Introduce the string:");
scanf("%s",searchingString);

while(fgets(s,128,fillle)!=NULL){

token = strtok(s ," ");

if(strcmp(token,searchingString) == 0)
printf("%s\n",searchingString);
else printf("0\n");
while (strtok!=NULL) {
token= strtok(NULL," ");
if(strcmp(token,searchingString) == 0)
printf("%s\n",searchingString);
else printf("0\n");
}
}
}

When I compile the file it doesn't give me any problem and when I try the program it prints on the monitor Introduce the string,but when I give it it says segmentation fault!
What's the problem?thanks!

Sorry for my English!

#2
JCoder

JCoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 245 posts
The error is here: const char searchingString[20]
Remove the const.

BTW: never, ever use scanf for reading data into buffers. Use fgets.

#3
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
>>while (strtok!=NULL) {

That is testing to see if a function address is NULL :w00t: I think you meant while( token != NULL ) {
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#4
fazla

fazla

    Newbie

  • Members
  • Pip
  • 2 posts

JCoder said:

The error is here: const char searchingString[20]
Remove the const.

BTW: never, ever use scanf for reading data into buffers. Use fgets.

Why this?

Anyway I've removed the const and this is my new code but it stills give me the same problem:

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

int main(){
char searchingString[20];
FILE *fillle= fopen("frase","r");
char s[512];
char *token;
printf("Introduci la stringa da cercare:");
scanf("%s",searchingString);
while(fgets(s,512,fillle)!=NULL){
token = strtok(s ," ");
if(strcmp(token,searchingString) == 0)
printf("%s\n",searchingString);
else printf("0\n");
while (strtok!=NULL) {
token= strtok(NULL," ");
if(strcmp(token,searchingString) == 0)
printf("%s\n",searchingString);
else printf("0\n");
}
}
}




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users