0
#include<stdio.h>
#include<stdlib.h>
#include<iostream.h>
#include<string.h>
void main(){

    FILE *fp1,*fp2;
    char *a,*b;
    int num;
    fp1=fopen("myfile.txt","r+");
    fp2=fopen("myfile.txt","a+");
    cout<<"enter the number of names you want to enter \n";
    cin>>num;
    a=(char*)malloc(80);
    b=(char*)malloc(80);
    while(num){
    gets(a);
    fputs("\n",fp2);
    fputs(a,fp2);
    num--;
    }
    cout<<"\n diplay the names";
    while(!feof(fp1)){
    fgets(b,80,fp1);
    cout<<b;
    }
/*
    //code to search string a in file ... i think logic is right but not able to find the answer
    cout<<"enter string for search";
    cin>>a;
    rewind(fp1);
    while(!feof(fp1) && strcmp(b,a)){
    fgets(b,80,fp1);
    }
    if(!strcmp(a,b))
        cout<<"name present";
        */
}
2
Contributors
1
Reply
11
Views
4 Years
Discussion Span
Last Post by Ancient Dragon
0

what are you entering for the search string? If it contains spaces then cin >> won't work because it stops after the first space. you should probably use cin.getline(a,80) so that it will keep the spaces.

The loop is a little off

while( fgets(b,80,fp1) && strcmp(b,a) )
   ;

notice that feof() isn't needed in the loop because fgets() will return NULL when eof is found.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.