if/else statement is not validating data [duplicate] - c

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 years ago.
I'm writing a code to better understand if/else statements, but I encountered a problem when trying to validate(?) a string, thanks for any help (C language)
#include <stdio.h>
#include <stdlib.h>
int main(){
char nametype[100];
printf("Enter the name type (firstname/lastname): ");
scanf("%s", &nametype);
script1(nametype);
return 0;
}
void script1(nametype){
char firstname[100];
int age;
char typename[100];
if(nametype == "firstname"){
char typename[100] = "first name.";
}
if(nametype == "lastname"){
char typename[100] = "last name.";
} else {
printf("You must enter the correct parameters! \n");
main();
}
printf("Enter your name: ");
scanf("%s", &firstname);
printf("Enter your age: ");
scanf("%d", &age);
printf("Hey! Your %s is %s, you're %d \n", typename, firstname, age);
}
I expect the code to proceed on to the end after I enter "firstname" or "lastname" in the first input, but instead it always proceeds to go to the else block.

You have a fundamental misunderstanding what the == operator does.
It doesn't compare strings. It compares pointers. If you write
char a[100] = "Hello";
char b[100] = "Hello";
then a == b while compare the pointers. a is a pointer to the array a, b is a pointer to the array b, the pointers are different, the comparison is false.
Use strcmp.
PS. That alone won't make your code work, because you are creating a second variable named "typename" in a nested block. It's a different variable than typename in the outer block, so this will have no useful effect whatsoever.

if(nametype == "firstname"){
char typename[100] = "first name.";
}
In this, nametype is compares to an char array "firstname" ,so you have to use strcmp(str1,str2) function.For use this function, you have to use header. It returns 0 if two strings are equal. Like this
if(strcmp(nametype,"firstname")==0){
// char typename[100] = "first name.";//
}
In the if condition, you have used typename variable which is already declared.So no need to re-declare this variable.
In C, it doesn't support the direct string or char array assignment.So you have to use strcpy(destination,source) function.So the code will be like this
if(strcmp(nametype,"firstname")==0){
strcpy(typename,"first name.");
}

Related

Printing ���� when adding a string to an array of strings [duplicate]

This question already has answers here:
Since I can't return a local variable, what's the best way to return a string from a C or C++ function?
(8 answers)
Return a string from function to main
(3 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 3 years ago.
I kept getting the error "Command terminated by signal 11" when I try to save a string into an array of strings. After changing the code from the link below, now the name prints out ���W.
I used this link to fix my code off of but it is still causing me to get the error "Command terminated by signal 11".
#include<stdio.h>
#include<string.h>
void getName(char* c[], int size);
int main(void) {
int yenoSize = 0;
int strSize = 0;
char name1[30];
char* name[30];
char* students[5][30];
for(int i=0;i<1;i++){
getName(name, strSize);
students[i][0] = name1;
}
for(int k=0; k<1;k++){
printf("Student Name: %s \n", students[k][30]);
}
}
void getName(char* c[], int size){
char name1[30];
printf("Enter student name: ");
fgets(name1, 30, stdin);
c[0] = &name1[0];
printf("%s", name1);
}
The output is supposed to print out the name that the user inputs (Student Name: Jon) but it is currently printing ���W. How can I fix the problem? I believe the problem exists with the name pointer pointing to null. Is that the problem? I appreciate the help!
2 major issues.
1) In main(), you are calling getName() with name but storing name1 in students variable.
2) In function getName(), name1 is a local array. The scope of this variable is limited to getName(). You can not return address of name1 by assigning it to c[0] as it may get freed by OS after function returns. You can consider using malloc() for this.

String comparison in if statement not working [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
I am new in C programming. Can you please advise, what's wrong with my code? It looks like the if statement is not working, and instead it's jumping and printing the else statement.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char profession;
printf("what is your profession? \n");
scanf(" %s", profession);
if(profession==“QA”)
{
printf(“Go and Test\n“);
}
else
{
printf("Do whatever you want");
}
return 0;
}
First of all, you can't compare strings like that in C. use strcmp or strncmp instead.
Secondly, in your code, profession is a char, and you want to put a string (several chars) in it. It won't work. You can create a char * (pointer on a char) (without forgetting to malloc() it) or a char [] (a char array).
Firstly, strings in C are array of characters, so you have to declare profession as a pointer, pointing to an array of characters. So that statement will look like this char* profession, secondly, you have to use a method called strcmp(char* a, char* b) that accepts two char pointers. This will return 0 if they are equal. I will include the answer, but I assume there are better ways of writing this code.
int main() {
char* profession;
char* compare = "QA";
printf("What is your profession?\n");
scanf(" %s", profession);
if(strcmp(profession, compare) == 0) {
printf("Go and Test\n");
} else {
printf("Do whatever you want");
}
return 0;
}

Is this a misunderstanding of the functionality of strcpy()?

#include <stdio.h>
#include <string.h>
int main(void) {
int number_of_members;
char family[number_of_members][20][number_of_members][20];
char member_name[20];
char birth_state[20];
char family_last_name[20];
printf("What is the last name of the family?\n");
scanf("%s", &family_last_name);
printf("How many members do you want to create?\n");
scanf("%d", &number_of_members);
int const FAMILY_SIZE = number_of_members;
number_of_members = number_of_members -1;
printf("Enter the family member name: \n");
for(number_of_members;number_of_members>-1;number_of_members--)
{
scanf("%s", &member_name);
strcpy(family[number_of_members], member_name);
printf(" %d %s %s\n",number_of_members, member_name, family_last_name);
}
printf("%s, %s ", family[0], family[1]);
return 0;
}
Here is the output:(from Ideone.com)
Ideone.com with code
The input to this code is: Layne , 2 , tim , jim.
When run, it shows the correct index with the name in the array however, once out it will show the last entered name, jim, as family1 and family[0]. Am I not understanding how strcpy() works? or is it a logic error?Some assistance soon would be appreciated!
This is very very wrong
int number_of_members;
char family[number_of_members][20][number_of_members][20];
Because you haven't initialized number_of_members.
Because it doesn't make sense whatsoever, it's not possible that you really need this kind of array.
And yes, if you enable compiler warnings it will hit you in your nose with a stick, because
strcpy(family[number_of_members], member_name);
shouldn't even compile and is undefined behavior since the type of family[number_of_members], is an array of arrays of arrays of char.
strcpy can take an array of char's because it will be automatically converted to a char poitner, and provided that the contents of the array comply with what a c string is, then strcpy() will work correctly, in your case the behavior is undefined because almost surely the '\0' will never be found in the destination pointer.
instead of
int num_of_members;
char family[number_of_members][20][number_of_members][20];
which is not C code, do this
#define MAX_MEMBERS 20
char family[MAX_MEMBERS][20];
which creates a rectangular array of arrays each of 20 bytes long

Pointer trouble, argument errors and general trouble in a very simple code

I recently got an assignment to write a code in C that determines if a list of words is sorted or not ("sorted"= all the words are in rising order of letters within the word)
We have many guidelines we have to follow, so the end result is outright stupid, instead of a short and efficient code.
I am getting 2 errors with my code:
"Passing argument 1 of 'sortedsentance' makes pointer from integer without a cast"
expected 'char *' but argument is of type 'char'
Here is my code-
#include <stdio.h>
int sortedSentance(char *str)
{
int i;
for (i=1; str[i]!='0'; i++)
{
if ((str[i]>str[i-1])||(str[i]==33))
continue;
else
break;
}
if (str[i]=='\0')
return 1;
else
return 0;
}
int main()
{
int num=0, val=0;
char str1;
printf("Please enter the number of strings of length 5 (maximum 5)\n");
scanf("%d", &num);
printf("Please enter %d strings\n", num);
scanf("%s", &str1);
val= (sortedSentance(str1));
if (val==1)
printf("the string %s, is sorted.", str1);
else
printf("the string %s, is not sorted.", str1);
return 0;
}
Notes:
Our guidelines press the function has to be declared like that, i know it should be done differently.
I know the variable num doesn't do anything, but again, for the sake of the stupid guidelines. The algorithm does it's desired function even without actually receiving the number of words from beforehand.
Any help would be much appreciated, I'm already grasping my hairs trying to make sense of why doesn't this very simple code work, and what kind of stupid mistake could i have done.
The problem is with your
char str1;
You try to use single char but in your function it accepts a pointer to a char array. This is the problem you have two options.
char str1[100];//This 100 could be changed according to your needs
2.
char * str1 = new char[100];//This 100 could be changed according to your needs
Either will work and remember to calls delete [] operator on str1 in the second case.
Moreover, I did't looked at logical correctness of your program. Just resolved your compilation error.
P.S.
Since the solution needs to be in C,
you may use
char * str1 = malloc(sizeof(char)*(100));
Instead of char str1; that is a holder for a single character you should allocate memory for a string, you can choose :
Static memory allocation : char str1[100];
Dynamic memory allocation : char *str1 = (char*) malloc(sizeof(char) * 100);
P.S. You don't have to pass to scanf the address of the string, because str1 is an address itself so write scanf("%s", str1); instead of scanf("%s", &str1);

Compare with string in if statement doesn't work

I try to compare my two strings that obtained from my scanf and fscanf. I already figured out what is the content inside the each variable. It both show the same strings, but after I compare with this two string in if statement, it doesn't work and execute else statement instead. What's wrong with my codes ?
int main(void)
{
...
char input[256];
printf("Enter your name: ");
scanf("%s",&input);
fp = fopen(_FILE,"r+");
for(i=0;i<textlines(_FILE);i++)
{
fscanf(fp,"%s %d",stuff[i].name,&stuff[i].salary);
if(input == stuff[i].name)
{
// Update name here
}
else
{
printf("Not Found");
}
}
return 0;
}
== just checks for pointer equality. Use strcmp instead
use the function strcmp in string.h library to compare your strings
As others have said, you need to use strcmp to compare strings (really character arrays). Also, you should not pass the address of name (i.e. &name) to the scanf() function.
You have this:
char input[256];
printf("Enter your name: ");
scanf("%s",&input);
....
if(input == stuff[i].name)
...
More correct code would include the following changes:
char input[256];
printf("Enter your name: ");
scanf("%s", input);
....
if (!strcmp(input, stuff[i].name))
....
You should check the definition and use of stuff[i].name as well. scanf() with a %s format character requires a simple char* parameter. The argument to strcmp() is const char* but using char* is fine and will be automatically promoted.
C is more flexible than other languages in that it allows you to obtain the address of variables. You create pointers to variables in this way. However, a variable declared as an array, such as input is already a pointer in a way. Only by providing an index to you dereference the pointer. Specifically:
char input[256];
input is a pointer to the storage of 256 char's
input can be thought of as a char* variable
input[0] is the first char in the array
input[1] is the second char in the array
input+1 is a pointer to the second char in the array.
input+0 (or simply input) is a pointer to the first char in the array.
&input is not good C form. You can kind of think of this as the address of the array but, in reality, input is already the address of the array. There is a use for such types of double-ly addressed variables but your case is not really one of them. Until you've had some practice with arrays and pointers (and their relationship) the following example might be a bit confusing but it does demonstrate where a char** variable might be used.
int allow_access_to_private_data(char ** data)
{
static char mystring[] = "This is a private string";
if (!data) return -1;
*data = mystring;
return 0;
}
int main(int argc, char* argv[])
{
char* string;
if (!allow_access_to_private_data(&string))
printf("Private data is: %s\n", string);
else
printf("Something went wrong!\n");
return 0;
}

Resources