Register for your free account! | Forgot your password?

Go Back   elitepvpers > Coders Den > C/C++
You last visited: Today at 15:59

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



Question

Discussion on Question within the C/C++ forum part of the Coders Den category.

Reply
 
Old   #1
 
Aeneis Boost's Avatar
 
elite*gold: 130
The Black Market: 116/0/0
Join Date: Mar 2009
Posts: 238
Received Thanks: 16
Question

Anyone can help me out with C?
strcmp is ******* me over it returns random numbers even tho when the 2 strings are equal and in some cases it even makes the program crash i couldnt really find anything helpful elsewhere... I can post the whole code if necccesary im just curious if anyone got time to help me.
Also anyone knows any alternative solution? (comparing 2 strings without strcmp)
Thanks in adavance.
Aeneis Boost is offline  
Old 12/22/2017, 23:30   #2
 
elite*gold: 0
Join Date: May 2015
Posts: 700
Received Thanks: 444
Sure, just post your code.

Are your strings null terminated? It's also possible that you **** up somewhere else and it's just a coincidence that it crashes at strcmp
algernong is offline  
Old 12/23/2017, 00:32   #3
 
Aeneis Boost's Avatar
 
elite*gold: 130
The Black Market: 116/0/0
Join Date: Mar 2009
Posts: 238
Received Thanks: 16
Code:
	
        char bekert[10];
	char b[1] = "i";
	int j;
	lines = countlines("beolvasas.txt");
	while(strcmp(b,"i")== 0)
	{
		
	printf("Milyen vércsoportra van szükség? "); scanf("%s", bekert);
	for(j=0;j<lines+1;j++){
		if(strcmp(blood[j].Vercsoport,bekert) == 0){
		printf("ID : %s\t",blood[j].ID);
		printf("Nev : %s\t",blood[j].Nev);
		printf("Vercsoport : %s\t",blood[j].Vercsoport);
		printf("Email : %s\t",blood[j].Email);
		printf("Verszam : %d\t",blood[j].Verszam);
		printf("Datum : %s\n",blood[j].Datum);
			}	
		}
		printf("Újra? (i/n))"); scanf("%s", b);
	}
It would basically search in an array of structure and it worked perfectly yesterday but now it wouldnt even go into the while because the "strcmp(b,"i")== 0" returns false numbers


also i have something similar for adding stuff into the array and saving it into a txt which works for me even now EVEN THO ITS THE SAME but it doesnt for my friend i dont get any of this

Oh yea also when the program gets to this "if(strcmp(blood[j].Vercsoport,bekert) == 0)" it crashes
ps. i can post the whole thing if needed
Aeneis Boost is offline  
Old 12/23/2017, 01:37   #4
 
elite*gold: 0
Join Date: May 2015
Posts: 700
Received Thanks: 444
The error is in line 2: make your char array "b" two chars long instead of one.

Strings in C are 0 terminated, i.e. a 0 is expected to follow the last byte of a string. Otherwise, functions couldn't determine the length of a passed string (remember: strings are merely pointers in C).

So why does strcmp fail? The array "b" only holds one byte, thus the 0 that follows your string is discarded.
You call strcmp, strcmp reads the first character from wherever "b" points to (= 'i') but since the next byte is not 0 (but some other random data; whatever comes next: could be undefined, could be some other variable, could be an invalid memory location), it thinks that your string continues. Thus, it reads more bytes until it either accesses an invalid memory location (-> program crashes) or a 0 appears by coincidence.

(That's what happens in general when you pass a string without 0 termination to a function; in this case, it probably stops reading bytes once it's at the end of "i", the second argument, since that's enough information to determine the outcome).

So "strcmp(b, "i") == 0" returns false numbers because "b" doesn't contain the string "i" but "i[random data]" instead.

If that doesn't fix all issues, you have probably more mistakes like this somewhere else in your code.
algernong is offline  
Old 12/23/2017, 02:06   #5
 
Aeneis Boost's Avatar
 
elite*gold: 130
The Black Market: 116/0/0
Join Date: Mar 2009
Posts: 238
Received Thanks: 16
okay you were absolutely correct thank you for that but the program still crashes when i try to search any idea about that one?
char bekert seems long enough(10) and still something is wrong when comparing
and also how the hell did these all work yesterday? am i high or something lol

Code:
int j;
	char b[2] = "i";
	FILE *file;
	printf("új tag hozzáadása\n");
   while(strcmp (b,"i") == 0)
   {
   	lines = countlines("beolvasas.txt");
	blood[lines].ID = lines+1;
   	printf("Név:\n"); scanf("%s",blood[lines].Nev);
	printf("Vércsoport:\n"); scanf("%s",blood[lines].Vercsoport);
	printf("Email:\n"); scanf("%s",blood[lines].Email);
	printf("Eddigi véradások száma:\n"); scanf("%d",&blood[lines].Verszam);
	printf("Utolsó véradás dátuma:\n"); scanf("%s",blood[lines].Datum);
	file = fopen("beolvasas.txt","a");
	fprintf(file,"%d\t%s\t%s\t%s\t%d\t%s\n",blood[lines].ID,blood[lines].Nev,blood[lines].Vercsoport,blood[lines].Email,blood[lines].Verszam,blood[lines].Datum);
	fclose(file);
	for(j=0;j<lines+1;j++){
		printf("Nev : %s\n",blood[j].Nev);
		printf("Vercsoport : %s\n",blood[j].Vercsoport);
		printf("Email : %s\n",blood[j].Email);
		printf("Verszam : %d\n",blood[j].Verszam);
		printf("Datum : %s\n",blood[j].Datum);
	}
	printf("Újra? (i/n))"); scanf("%s", b);
   }
heres the other ones code now just in case you need it and i also declared
struct Blood blood[10]; outside of these and this is my structure

Code:
struct Blood{
	int  ID;
   char  Nev[50];
   char  Vercsoport[50];
   char  Email[100];
   int   Verszam;
   char  Datum[50];
};
Aeneis Boost is offline  
Old 12/23/2017, 16:39   #6
 
elite*gold: 0
Join Date: Apr 2011
Posts: 363
Received Thanks: 167
Quote:
Originally Posted by Aeneis Boost View Post
okay you were absolutely correct thank you for that but the program still crashes when i try to search any idea about that one?
char bekert seems long enough(10) and still something is wrong when comparing
and also how the hell did these all work yesterday? am i high or something lol

Code:
int j;
	char b[2] = "i";
	FILE *file;
	printf("új tag hozzáadása\n");
   while(strcmp (b,"i") == 0)
   {
   	lines = countlines("beolvasas.txt");
	blood[lines].ID = lines+1;
   	printf("Név:\n"); scanf("%s",blood[lines].Nev);
	printf("Vércsoport:\n"); scanf("%s",blood[lines].Vercsoport);
	printf("Email:\n"); scanf("%s",blood[lines].Email);
	printf("Eddigi véradások száma:\n"); scanf("%d",&blood[lines].Verszam);
	printf("Utolsó véradás dátuma:\n"); scanf("%s",blood[lines].Datum);
	file = fopen("beolvasas.txt","a");
	fprintf(file,"%d\t%s\t%s\t%s\t%d\t%s\n",blood[lines].ID,blood[lines].Nev,blood[lines].Vercsoport,blood[lines].Email,blood[lines].Verszam,blood[lines].Datum);
	fclose(file);
	for(j=0;j<lines+1;j++){
		printf("Nev : %s\n",blood[j].Nev);
		printf("Vercsoport : %s\n",blood[j].Vercsoport);
		printf("Email : %s\n",blood[j].Email);
		printf("Verszam : %d\n",blood[j].Verszam);
		printf("Datum : %s\n",blood[j].Datum);
	}
	printf("Újra? (i/n))"); scanf("%s", b);
   }
heres the other ones code now just in case you need it and i also declared
struct Blood blood[10]; outside of these and this is my structure

Code:
struct Blood{
	int  ID;
   char  Nev[50];
   char  Vercsoport[50];
   char  Email[100];
   int   Verszam;
   char  Datum[50];
};
You r high indeed, because u open and close the same file inside a loop.
Code:
file = fopen("beolvasas.txt","a");
	....
	fclose(file);
Pretty sure that your crash is for arrayoutofbounds exception, here,
you said blood is array structure of 10, don't know why you count file lines, but make sure it goes to 10 or less.
lines+1-> this have to be <=9
Code:
for(j=0;j<lines+1;j++){
		printf("Nev : %s\n",blood[j].Nev);
		printf("Vercsoport : %s\n",blood[j].Vercsoport);
		printf("Email : %s\n",blood[j].Email);
		printf("Verszam : %d\n",blood[j].Verszam);
		printf("Datum : %s\n",blood[j].Datum);
	}
elmarcia is offline  
Old 12/23/2017, 19:19   #7
 
Aeneis Boost's Avatar
 
elite*gold: 130
The Black Market: 116/0/0
Join Date: Mar 2009
Posts: 238
Received Thanks: 16
Code:
	for(j=0;j<lines+1;j++){
		if(strcmp(blood[j].Vercsoport,bekert) == 0){
		printf("ID : %s\t",blood[j].ID);
		printf("Nev : %s\t",blood[j].Nev);
		printf("Vercsoport : %s\t",blood[j].Vercsoport);
		printf("Email : %s\t",blood[j].Email);
		printf("Verszam : %d\t",blood[j].Verszam);
		printf("Datum : %s\n",blood[j].Datum);
			}
My problem is with this part of the code and its not arrayoutofbounds but i fixed the other mistake
Aeneis Boost is offline  
Old 12/23/2017, 19:52   #8
 
elite*gold: 0
Join Date: Apr 2011
Posts: 363
Received Thanks: 167
printf("ID : %s\t",blood[j].ID); -> printf("ID : %i\t",blood[j].ID); is integer, the code looks good


Edit:
also i have something similar for adding stuff into the array and saving it into a txt which works for me even now EVEN THO ITS THE SAME but it doesnt for my friend i dont get any of this

your friend should execute the program with admin rights to write files with no errors.
elmarcia is offline  
Old 12/23/2017, 20:10   #9
 
elite*gold: 0
Join Date: May 2015
Posts: 700
Received Thanks: 444
Can you show the complete code?
+ the file that you read + everything that you enter when you execute it
(I don't see any more obvious errors, assuming your arrays are big enough)
What does countlines do (and how is it implemented)?
What's the definition of your blood array?

Code:
file = fopen("beolvasas.txt","a");
Check whether file is NULL (= file could not be opened due to some error).

Are you on Linux? If so, install valgrind (should be available in your package manager's repo) and execute your program with valgrind, then post the output. e
algernong is offline  
Old 12/23/2017, 20:21   #10
 
Aeneis Boost's Avatar
 
elite*gold: 130
The Black Market: 116/0/0
Join Date: Mar 2009
Posts: 238
Received Thanks: 16
Code:
#include <stdio.h>
#include <time.h>
#include <string.h>

int countlines(char *filename)
{                              
  FILE *fp = fopen(filename,"r");
  int ch=0;
  int lines=0;

while(!feof(fp))
{
  ch = fgetc(fp);
  if(ch == '\n')
  {
    lines++;
  }
}
  fclose(fp);
  return lines;
}

struct date{

    int month;
    int day;
    int year;

};
struct Blood{
	int  ID;
   char  Nev[50];
   char  Vercsoport[50];
   char  Email[100];
   int   Verszam;
   char  Datum[50];
};
main ( )
{
struct Blood blood[10];
struct date datum;
int a;
do {

time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("ÜVDÖZLI ÖNT A VÉRADÓK NYILVÁNTARTÁSÁT SEGÍTŐ PROGRAM! \n");
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
("Kérem adja meg a mai dátumot! (pl.: 2017.09.01., majd enter):");   
system("@cls||clear");
printf("-1: Taglista megtekintése\n");   
printf("-2: Új tag hozzáadása a listához\n");
printf("-3: Adott vércsoport keresése\n");  

int lines = countlines("beolvasas.txt");

printf("Az ön választása :");scanf("%d",&a);

system("@cls||clear");
if(a==1){
char bekert[1];
int c;
char b[1] = "i";
FILE *file;
file = fopen("beolvasas.txt", "r");
printf("VÉRADÓINK NYILVÁNTARTÓ FÁJLJÁNAK LISTÁJA\n ");
printf("ID \t NÉV \t VÉRCSOPORT \t EMAIL \t VÉRADÁSOK SZÁMA \t UTOLSÓ VÉRADÁS DÁTUMA\n__________________________________________________________________________________________\n");
if (file) {
    while ((c = getc(file)) != EOF)
        putchar(c);
    fclose(file);
}
printf ("tovább fusson a program?(i/n) ");	scanf("%s",bekert);
if(strcmp (bekert,"n") == 0){
	printf("A program leáll");
	exit(1);
}
}
if (a == 2){
	int j;
	char b[2] = "i";
	FILE *file;
	printf("új tag hozzáadása\n");
   while(strcmp (b,"i") == 0)
   {
   	lines = countlines("beolvasas.txt");
	blood[lines].ID = lines+1;
   	printf("Név:\n"); scanf("%s",blood[lines].Nev);
	printf("Vércsoport:\n"); scanf("%s",blood[lines].Vercsoport);
	printf("Email:\n"); scanf("%s",blood[lines].Email);
	printf("Eddigi véradások száma:\n"); scanf("%d",&blood[lines].Verszam);
	printf("Utolsó véradás dátuma:\n"); scanf("%s",blood[lines].Datum);
	file = fopen("beolvasas.txt","a");
	fprintf(file,"%d\t%s\t%s\t%s\t%d\t%s\n",blood[lines].ID,blood[lines].Nev,blood[lines].Vercsoport,blood[lines].Email,blood[lines].Verszam,blood[lines].Datum);
	
	for(j=0;j<lines+1;j++){
		printf("Nev : %s\n",blood[j].Nev);
		printf("Vercsoport : %s\n",blood[j].Vercsoport);
		printf("Email : %s\n",blood[j].Email);
		printf("Verszam : %d\n",blood[j].Verszam);
		printf("Datum : %s\n",blood[j].Datum);
	}
	printf("Újra? (i/n))"); scanf("%s", b);
   }
	fclose(file);
   }
if (a == 3){
	char bekert[3];
	char b[2] = "i";
	int j;
	lines = countlines("beolvasas.txt");
	while(strcmp(b,"i")== 0)
	{
		
	printf("Milyen vércsoportra van szükség? "); scanf("%s", bekert);
	for(j=0;j<lines+1;j++){
		if(strcmp(blood[j].Vercsoport,bekert) == 0){
		printf("ID : %s\t",blood[j].ID);
		printf("Nev : %s\t",blood[j].Nev);
		printf("Vercsoport : %s\t",blood[j].Vercsoport);
		printf("Email : %s\t",blood[j].Email);
		printf("Verszam : %d\t",blood[j].Verszam);
		printf("Datum : %s\n",blood[j].Datum);
			}	
		}
		printf("Újra? (i/n))"); scanf("%s", b);
	}

}
}while(a<4 && a>0);
}
alright here's everything it basically has a menu (i know i could do it with switch case but yea well i have this now) you either press 1 2 or 3 that brings you to different stuff the txt i read is completely empty i add stuff at the "2" and i wanna basically search around bloodtypes and print them at "3" Vercsoport = Bloodtype
Theres nothing to check for valid inputs yet
countlines basically just counts the lines of the txt file so i can use that for ID and to search in the blood array of struct
To check it i press 2 on the menu then add some random stuff and then back out from the while cycle then press 3 and try to search what i just wrote in the array

ps. dont mind the first few lines of the code i just clear them out also im open for ideas about checking for valid email (it has @ and . and not like this @. + valid date like this "2012.12.12.")
Aeneis Boost is offline  
Old 12/23/2017, 21:40   #11
 
elite*gold: 0
Join Date: May 2015
Posts: 700
Received Thanks: 444
1. The program crashes if "beolvasas.txt" doesn't exist: In this case (in function countlines)
Code:
FILE *fp = fopen(filename,"r");
returns "NULL", thus you call
Code:
while(!feof(NULL))
, but feof expects a valid FILE* pointer.

Solution: Check the return value of fopen! If it's NULL, create the file or show your own error message and halt execution.

2. Fix the declaration of main, it's lacking its return type (should be int).

3. Include stdlib.h for system() and exit()

4. You still have
Code:
char b[1] = "i";
in case a = 1.

5.
Code:
printf("ID : %s\t",blood[j].ID);
blood[j].ID is int, thus %d instead of %s

6. As elmarcia pointed out, your loops are wrong:
Code:
for(j=0;j<lines+1;j++){
should be (remove the +1)
Code:
for(j=0;j<lines;j++){
If your file contains, say, 5 lines, then the loop iterates over the first 5 elements in the array: 0, 1, 2, 3, 4

7. Are you aware that you never load the txt file? If the file already contains some lines and you start the program, the blood array is empty; thus, selecting 3 in the menu could cause the program to crash because blood contains random data. Thus, strings have random length (because there's no 0 termination), thus strcmp or the printf's could access invalid memory locations. The same thing happens in case a == 2.

8. Your "fclose" in case a == 2 is at the wrong location; you open the file within the loop but close it outside the loop.

Oh and try to indent your code properly
algernong is offline  
Old 12/23/2017, 22:02   #12
 
Aeneis Boost's Avatar
 
elite*gold: 130
The Black Market: 116/0/0
Join Date: Mar 2009
Posts: 238
Received Thanks: 16
Well im fairly new to programming and really really new to c but well im trying to learn

the other guy just called me a ****** for closing the file inside the loop am not supposed to do that or where do i close it?

also good catch on that ID it sure is an integer and that caused that crash that drove me crazy.

and yes im aware of everything else thats kind of in the todo list
also the main always has to be int? cant it be just void or something like everywhere else?
thanks for everything man and everyone else too! it seems to be working now

and also my last question remains about the date checking and email checking if anyone has some time for it
Aeneis Boost is offline  
Old 12/23/2017, 22:32   #13
 
elite*gold: 0
Join Date: May 2015
Posts: 700
Received Thanks: 444
Place the fopen() before the loop so that you call it only once. fclose() after the loop is fine then.

Yep, main must always return int. It's the application's exit code and is used to determine whether your application succeeded in doing whatever it was supposed to do (= exit code 0) or failed (= any other exit code).

E.g.
Quote:
λ ~/ cat doesntexit
cat: doesntexit: No such file or directory
λ ~/ echo $?
1
λ ~/ cat test.c
void main() {}
λ ~/ echo $?
0
"echo $?" prints the exit code of the last application; in the first case, cat can't print the content of "doesntexist" because the file doesn't exist. Thus, it's main function returned 1 to indicate that there was an error. If the file exists and can be read by cat, it returns 0, indicating that there was no error.

To validate the e-mail address, loop through the string character by character:
Code:
char *str = "email";
for (int i = 0; str[i] != 0; ++i) {
  char c = str[i];
  // todo
}
Then keep track of which symbols you've already discovered and check for errors, e.g. like this (didn't test it):
Code:
int pos_at = -1; // -1 = no at yet
int pos_last_dot_after_at = -1; 
for (int i = 0; str[i] != 0; ++i) {
  char c = str[i];
  if (c == '@') {
    if (i == 0) { return 0; } // invalid email, starts with @
    if (pos_at != -1) { return 0; } // invalid email, contains 2 or more @
    pos_at = i;
  } else if (c == '.') {
    if (i == 0) { return 0; } // invalid email, starts with .
    if (pos_at > 0) { // we're after the @
      if (pos_at + 1 == i) { return 0; } // invalid email, . right after @
      pos_last_dot_after_at = i;
    }
  }
}

if (pos_at == -1 || pos_last_dot_after_at == -1) { return 0; } // invalid email, contains no @ or no . after @
return 1; // maybe valid
You could validate the date in a similar way. You could also take a look at <string.h>, maybe there are some functions that help you.
algernong is offline  
Thanks
1 User
Old 12/24/2017, 01:00   #14
 
Aeneis Boost's Avatar
 
elite*gold: 130
The Black Market: 116/0/0
Join Date: Mar 2009
Posts: 238
Received Thanks: 16
it looks clever, thanks man i'll test it tomorrow
and thanks for the info and of course everything else too
Aeneis Boost is offline  
Reply


Similar Threads Similar Threads
Bot question...stupid question by the way
12/05/2007 - Conquer Online 2 - 5 Replies
ok i have this litlle problem with CoPartener..that is i cant find it...i looked where i found it before...but when i download it...BOOM...just S3DHook.dll ....evreywhere i look..the same thing...can anybody help me...help a poor noob....by the way...got weed?text2schild.php?smilienummer=1&text=WEEEE EED!' border='0' alt='WEEEEEED!' />



All times are GMT +1. The time now is 16:00.


Powered by vBulletin®
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2025 elitepvpers All Rights Reserved.