Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Just started. nedd help

Status
Not open for further replies.

VBakias

MIS
May 24, 2005
219
GR
Hi,
This is my code

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

int sig(char [], char []);


void main()
{
  char a[30];
  char b[30];
  
  scanf("%s", &a);
  scanf("%s", &b);

  printf("%d\n",sig(a,b));
}

int sig(char a[], char b[])
{
  int i;
  for (i=0; strlen(a); i++)
  {
    if (a[i] != b[i])
      return(0);
  }
  return(1);
}



This is supposed to tahe two strings in a char array and compare them cell by cell. If one cell is not equal to the other at the second array (a != b) the function should return 0. If the condition in the if statement never gonna be true, as the for loop finishes it will return1.

It always return 0.

? tnx
 
> void main()
main returns an int

> for (i=0; strlen(a); i++)
You need an explicit comparison. You've written
for (i=0; strlen(a) != 0 ; i++)

> scanf("%s", &a);
Drop the & here - a is an array
scanf("%s", a);


--
 
In the future, you should probably ask questions about C code in a C forum. This time, your problem looks to be a simple error in the control for your for loop. The way the code is currently written, you are looping while strlen(a) is true (i.e. non-zero), which will always be the case unless a is empty. So the loop continues forever, or until the inner if statement leads to a return 0.

What you probably wanted to do was loop while i is less than strlen(a). So to fix the problem just modify the for loop with that change.
 
Thanks, i modified a little:

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

int sig(char [], char []);


void main()
{
char a[30];
char b[30];

scanf("%s", &a);
scanf("%s", &b);


printf("%d\n",sig(a,b));
}

int sig(char a[], char b[])
{

int i;
for (i=0; i<30; i++)
{
if (a != b)
return(0);
}
return(1);
}



I still don't get 2 things
1. with or without the "&" works fine. ?

2. i've declared that the char a[] will be 30 cells.
I can also write: char a[]="hello"; without a number
Is there any way to do something like this: char a[]=read_from_keyboard. Tried this:
char a[];
scanf("%s",&a); // but not working because i've not declared the size of a.

The purpose of this is to sheck first is strlen(a)==strlen(b). If not then definately the strings will not be equal. If yes then i have to check it out.


Tnx
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top