hi guys...i have a problem concerning strcmpi not equal while inside a while loop. Check out my code below:

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

main()
{
      char yr[4],new_yr[4];
      int x=0;
      FILE *fp1;
      printf("Enter Year: ");scanf("%s",new_yr);
      printf("\n");
      printf("You Entered Year %s\n\n",&new_yr);
      if(strlen(new_yr)==4)
      {
      fp1=fopen("year.txt","r");
      while(fscanf(fp1,"%s",yr)>0)
      {
                             if(strcmpi(yr,new_yr)!=0)
                             {

                             fp1=fopen("year.txt","a");

                             fprintf(fp1,"\n%s",new_yr);
                             fclose(fp1);
                             x=1;
                             }

      } 
      if(x==1) printf("Successfully added!!\n\n");
      else if(x==0)printf("year already exist!!\n\n");
      }

      else printf("Invalid Input!!");

      printf("\n\n");
      system("pause");
}

my program is about adding a new year and comparing it if there is no duplicate year the computer will add it to the file.
algorithm:

Enter Year: user input (e.g. 2007)

content of year.txt:
2003
2004
2005

if i enter 2007 the computer suppose to comparing it to 2003,2004,2005 if it has no duplicate it will add it to the file else the computer will say that Year already exist.

my problem is i think it doesnt compare, when i inputed 2007, the computer will add it plus the 2003...
and when i enter the year 2003 that i know already exist, computer will still add it.

can you guys tell me what is the problem in my code?

Add a boolean variable in the beginning of the program.
bool found=false;
( or if you don't use booleans just use an int with 0 or 1 like your X variable)

inside the while loop keep the strcmpi but like this
if(!strcmpi(yr,new_yr))
and change the boolean value to true and break; ( because you have found the same year already )

now when you check the for the boolean value , then perform the insertion to the file.
and you are done ( I hope ;) )

also if i'm not mistaken the
else printf("Invalid Input!!");
will never be true
since x is only 1 or 0.

give me an update

i'm sorry but i'm a newbie in this... bool found=false? i dont know where to put that on my code.

can you retype my code?

and the:
else printf("Invalid Input!!");
can be true because its pair up with:
if(strlen(new_yr)==4)
if the user inputs <4 or >4 strings, the statement will be true.

sorry for my bad english and bad indents.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.