Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm making a simple code in C programming. To Be Honest with you guys I have quite a while that I don't program in it. So I wanted to make a simple program to reintroduce myself to this programming language.
This is the code:
#include <stdio.h>
#include <string.h>
int main()
{
char email;
char temppass[64];
char pass[] = "password";
printf("Enter your email: \n");
scanf("%s", &email);
printf("Enter your password: \n");
scanf("%s" , &temppass);
if(strcmp(temppass, pass) == 0){
printf("This is the password");
}
else{
printf("You Failed!");
}
return 0;
}
Though I'm having some problems which I can't solve. The first problem is that it is giving me an warning:
strcmp2.c: In function ‘main’:
strcmp2.c:14:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[64]’ [-Wformat=]
scanf("%s" , &temppass);
~^ ~~~~~~~~~
I'm pretty aware that this question might look duplicate as other questions but as far as I have searched and read all questions and answers, none of them could help me since they were different and didn't helped me.
At first, I tried to solve it with fgets() as an input function. When compiling the code, it didn't gave me nor warnings or errors but the problem with it is that fgets puts a \n new line character at the end of input. So the user input and the string I'm comparing are not the same. I tried adding the new line character at char pass[]="password\n" to see if it solves anything, but it failed again.
Though, when I run it and inputs the requested info, the strcmp() function will not successfully compare the two strings, even if the password input is the same.
If anyone would help me, I really appreciate you and your precious time. Many Thanks In Advance :)
The reason that your password test isn't working is related to the warning. When temppass is declared as an array, it is really a pointer to statically allocated memory. So when you take the address of it, you are no longer pointing to the beginning of the array you are pointing to a variable who's value points to the beginning of the array. The situation is similar to this code:
char *c = malloc(42);
scanf("%s", &c);
As you can see, we are giving scanf a char ** not a char *.
As others have noted, the email variable should probably be an array as well, and the call to scanf should not take the address of email at that point either.
Additionally, it is best to explicitly initialize your variables and bound your input. For the former, if you are compiling without optimizations then the compiler is probably zeroing out your memory already, but when you get into production code uninitialized variables are dangerous. Similarly, since the input is being placed into statically allocated arrays scanf should be told to limit the number of characters it copies.
#include <stdio.h>
#include <string.h>
int main()
{
char email[64] = { 0 };
char temppass[64] = { 0 };
char pass[] = "password";
printf("Enter your email: \n");
int scanf_return_value = scanf("%63s", email);
if (scanf_return_value != 1) {
printf("Error parsing input!\n");
if (scanf_return_value == EOF) {
perror("scanf");
} else {
printf("scanf returned unexpected value %d", scanf_return_value);
}
}
printf("Enter your password: \n");
scanf_return_value = scanf("%63s" , temppass);
if (scanf_return_value != 1) {
printf("Error parsing input!\n");
if (scanf_return_value == EOF) {
perror("scanf");
} else {
printf("scanf returned unexpected value %d", scanf_return_value);
}
}
if(strcmp(temppass, pass) == 0) {
printf("This is the password");
}
else {
printf("You Failed!");
}
return 0;
}
email can only store one character, not a string. And you don't need the & in the scanf when you give the address of the array (temppass is &temppass[0]).
try this instead:
char email[64];
char temppass[64];
char *pass = "password";
printf("Enter your email: \n");
scanf("%s", email);
printf("Enter your password: \n");
scanf("%s" , temppass);
Beware that the way you read your string is not safe if the length of the input is greater than the length of the string.
The compiler is complaining because the type of &temppass is, as it says, pointer-to-array-of-char; with scanf, the "%s" specifier expects a pointer-to-char. Easy to fix. Change
scanf("%s" , &temppass);
to
scanf("%s" , temppass);
that is, remove the &.
email variable is a single character, and you are trying to pass a string into it.
Make it email[50]; and remove the & in scanf when you're reading a string from stdin, this is what triggers the warning.
Related
I'm a little new to C programming but have some experience. To test my skills, I was trying to build a Bank management program that allows you to create your account, make deposits/withdrawals, etc. The code that I have so far is:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
char username[20];
char password[20];
void create_account(char* usrname, char* passwd) {
printf("==================================CREATE BANK ACCOUNT==================================\n");
while(1) {
printf("Enter a username that is less than 20 characters: ");
scanf("%s", usrname);
if (strlen(usrname) <= 20)
break;
printf("That is not less than 20 characters, try again...\n");
}
while(1) {
printf("Enter a password that is less than 20 characters: ");
scanf("%s", passwd);
if (strlen(passwd) <= 20) {
break;
}
}
printf("Thank you, please sign in now...\n");
sleep(2);
}
int main(void) {
create_account(username, password);
printf("\n%s", username);
printf("\n%s", password);
return 0;
}
I am aware that I have no parameters when I'm calling the function in main but that's because I don't know what parameters to pass through in the function declaration/initialization so for now, I keep it blank. My question is how do I pass 2 arrays into a function, ask the user to create a username and password, store it in their respective arrays and return both arrays to the program? I know it has to do something with pointers but don't know what to do. I know there is a way to do this with structures too but I don't know anything about that, unions, typedefs, or anything advanced. I really am a novice so please, if the answer is simple, don't get mad at me. Thanks in advance!
Edit: I've read through everyone's comments and answers and made the necessary changes to the code except for the one where someone mentioned using fgets instead of scanf. I don't really understand what to do so I just left it, despite the fact that he said scanf is just as dangerous as gets. I think I got everything but if someone has something else, please let me know. Thank you everyone.
What you can do is create 2 global arrays :
char username[20];
char password[20];
Note that the variables aren't pointers.
Then in the argument passed to the function create_account, you receive pointers that point to the addresses of the two arrays created :
void create_account(char* usrname, char* passwd) {
/* code... */
}
Remember, the asterisk means "the contents of address...".
To validate the the user's input, I prefer using an infinte loop. The program will break out of the loop once the user enters a valid username (the same can be done for the password) :
while(1) {
printf("Enter a username that is less than 20 characters: ");
scanf("%s", usrname);
if (strlen(usrname) <= 20)
break;
printf("That is not less than 20 characters, try again...\n");
}
Finally, in the main function when calling create_account, you pass the array variables :
int main(void) {
create_account(username, password);
return 0;
}
Just before the return statement you can print out the entered username and password :
printf("\n%s", username);
printf("\n%s", password);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm new to C,and want to write a simple program that takes a user input and prints it out a specific amount of times back to them.
#include <stdio.h>
#include <stdlib.h>
int main() {
char* str[100];
int *p = malloc(sizeof(int) * 10);
int amount;
*p = amount;
int i;
printf("\nType anything!\n");
scanf("%s", str);
printf("\nHow many times?\n");
scanf("%d", amount);
for (i=0; i<=amount; i++) {
printf("%s", str);
}
return 0;
}
It works fine,until after pressing entering the amount of times,when the program crashes with the Fish shell saying "fish: “./a.out” terminated by signal SIGSEGV (Address boundary error)".
Address boundary error tells me that maybe I haven't allocated memory for something,but how would I go about doing that? I've tried using malloc with a pointer pointed at amount but it doesnt seemed to have solved anything.
It's remarkable how many issues there are in such a short chunk of code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[100];
int amount;
printf("\nType any word!\n");
if (scanf("%99s", str) != 1)
{
fprintf(stderr, "Failed to read a string\n");
return(EXIT_FAILURE);
}
printf("\nHow many times?\n");
if (scanf("%d", &amount) != 1)
{
fprintf(stderr, "Failed to read an integer\n");
return(EXIT_FAILURE);
}
for (int i = 0; i < amount; i++)
{
printf("%s\n", str);
}
return 0;
}
The signature of main() is a full prototype.
The type of str is corrected (or, at least, changed and made usable).
The code related to p and malloc() is not needed.
The variable i is moved into the for loop (assumes a C99 or later compiler; if not available, what you had was OK).
Change "anything" to "any word" because %s skips white space and then reads non-spaces up to the next white space.
Limit the amount of input to prevent overflows.
Report if there's a problem reading the string and exit.
Fix the scanf() to pass &amount (key change).
Check for success reading amount and report failure and exit.
Define i in the loop control (C99).
If the user requests one copy, only print one copy (change <= to < — that's an idiomatic C loop now).
Output newline after each word. There are other ways to present the data, including the one chosen originally, but you should at least end the output with a newline.
I'm just practicing C and I would like to make a simple Login program with a username and a password... here is my code:
int main(){
char uname, passwd;
printf("Enter your username: ");
scanf("%c", uname);
printf("Enter your password: ");
scanf("%c", passwd);
printf(" \n");
if (uname == "waw" && passwd == "wow"){
printf("You have logged in\n");
} else {
printf("Failed, please try again\n");
}
return 0;
}
And then I got this error when I try to compile it
log.c: In function ‘main’:
log.c:7:10: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%c", uname);
^
log.c:9:10: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%c", passwd);
^
log.c:13:14: warning: comparison between pointer and integer
if (uname == "waw" && passwd == "wow"){
^
log.c:13:33: warning: comparison between pointer and integer
if (uname == "waw" && passwd == "wow"){
^
1) Don't read (scan) into a char. You need a string. Use format specifier %s instead of %c
2) Use strcmp to compare string values
Try this:
#include <stdio.h>
int main(){
int res;
char uname[40]; // char arrays instead of single char
char passwd[40];
printf("Enter your username: ");
res = scanf("%39s", uname); // Set a maximum number of chars to read to
// 39 to avoid overflow
if (res != 1) exit(1); // Error on stdin. End program
printf("Enter your password: ");
res = scanf("%39s", passwd);
if (res != 1) exit(1); // Error on stdin
printf(" \n");
// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are identical
if ((strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0)){
printf("You have logged in\n");
} else{
printf("Failed, please try again\n");
}
return 0;
}
There is no string data type in C programming language. Strings in C are represented as array of characters.
In C, char is a data type to represent a character. So, all you need to do is declare a array of char data type to represent a string in C. Each element in that array will hold a character of your string.
Also, operators in C like ==, !=, +=, + are defined for build-in data types in C and since, there is no operator overloading in C, you can't use these operators with your C-String as C-Strings are not build-in data type in C programming language.
Note: C-Strings are actually Null-terminated array of char data types. That means, last character in any C-String in C will be used to store a Null Character ('\0') which marks the end of the string.
The Header file <string.h> has predefined functions that you can use to operate on C-String(Null-terminated array of char data type). You can read more about it over here.
So, your program should look like:
#include <stdio.h>
#include <string.h>
#define CSTR_MAX_LEN 100
int main()
{
char uname[CSTR_MAX_LEN+1]; //An extra position to store Null Character if 100 characters are to be stored in it.
char passwd[CSTR_MAX_LEN+1];
printf("Enter your username: ");
scanf("%s", uname);
printf("Enter your password: ");
scanf("%s", passwd);
// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are identical
if ((strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0)){
printf("You have logged in\n");
} else{
printf("Failed, please try again\n");
}
return 0;
}
Remember, the correct format specifier to handle C-Strings are %s in C programming language. So, i have to change your scanf() function call. Also, i have used strcmp() function which is declared in header file <string.h> (i have included this header file in the above program). It returns numeric zero if strings match. You can read more about it above here. Also, have a look at strncmp() which is safer version of strcmp(). Also, remember that it can lead to undefined behavior if you try to access any array out of it's bound. So, it would be good idea to include checking in your program. As, someone included in their answer you can change my scanf() function call to:
scanf("%100s", uname);
It avoids to read more than 100 characters in array uname as it is allocated only to store 100 characters(excluding the Null character).
This is how you can do it with milkstrings
tXt ask(tXt prmp) {
printf("%s ?",prmp) ;
return(txtFromFile(stdin)) ; }
void main(void) {
tXt user = ask("user") ;
if ( strcmp(txtConcat(user,"/",ask("password"),NULL),"waw/wow") == 0)
printf("You have logged in\n");
else
printf("Failed, please try again\n");
}
First of all, you have declared uname and passwd as single characters, but you want to read strings. So you need to define the maximum length for each one and declare them as following:
char [X] uname; //where X is the maximum length for uname, for instance 25
char [Y] passwd; //where Y is the maximum length for passwd, for instance 20
Accordingly, your scanf() function should then be modified to :
scanf("%s", uname);
scanf("%s", passwd);
Apart from that, you need strcmp() to compare a string with a value. Change your if statement to :
if ( (strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0) ) {
printf("You have logged in\n");
This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 6 years ago.
I'm a newbie learning to program in C, and I am currently working on creating a program that takes a name input from a user then prints that name back on to the screen. When the program prints out the name in the else if block, what I get is $ ". I want to know why it happens and how I might correct this problem. My code is as follows:
#include <stdio.h>
#include <stdlib.h>
int main() {
char * ans; // yes/no answer
char * name; //name variable
printf("Welcome to the program. Would you like to begin? (y/n)\n");
scanf("%s", ans);
if (strcmp(ans, "y") != 0) {
printf("Have a good day!\n");
return 0;
}
else if (strcmp(ans, "y") == 0)
printf(" %s\n", ans);
printf("Okay, input your name:\n");
scanf("%s", name);
printf(" %s", name);// I get $ " rather than the name.
return 0;
}
You are using scanf() to read characters from the user, but haven't allocated any memory to hold those characters. This gives undefined behavior, as "anything can happen" when you break the rules like that.
Make those uninitialized pointers into arrays instead:
char ans[128];
char name[128];
This gives you 128 characters of space for each string (one of which will be used by the terminator).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
while i am running the above title is appearing as error
#include <stdio.h>
int main()
{
int i;
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s",name);
while(name[i]!="\0")
{
i++;
if(name[i]==" ")
{
strcpy(b[i],name[i]);
printf("copied name: ");
scanf("%s",b[i]);
}
}
}
while i am running this it is showing this error why? warning: comparison between pointer and integer.
"\0" is a string, '\0' is a character. As you comparing a character, you need the latter.
Also, as pointed out by chqrlie, there are many other issues - you need to check your compiler warnings/errors and fix them all. For example,
name[i]==" " is wrong with the same reason.
where is b declared?
where is i initialized??
There are many errors/ warnings in your code.
It should be '\0'. Not "\0";
You have not declared b[];
Initialize i=0;
Instead of strcpy, you can use another method which is shown in below code.
Also, you should not use scanf in last line. You should use printf. scanf is used to take input from user. printf is used to print the results.
Code-
#include <stdio.h>
int main()
{
int i=0,n;
char name[20],b[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s\n",name);
while(name[i]!='\0')
{
b[i]=name[i]; // to copy from name[] to b[]. Instead of strcpy
i++;
}
printf("copied name: ");
for(n=0;n<=i;n++)
{
printf("%c",b[n]); // to show the copied result.
}
printf("\n");
return 0;
}