Why will this simple C program not run? [closed] - c

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
This code will not run. Can somebody tell me why?
#include <stdio.h>
#include <string.h>
main (){
char user[7];
printf("Username\n");
scanf("%s",user);
if(user == 'admin'){
printf("Hello World");
}else{
printf("Bad");
}
return(0);
}

This is a working example. You need to use strcmp to compare strings. strcmp() returns 0, if the strings are equal.
If the max input length is known, then you should also use length specifier in scanf or one of the suggestion listed here, to prevent a buffer overflow.
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv)
{
char user[7];
printf("Username:\n");
scanf("%6s", user);
if(!strcmp(user, "admin"))
{
printf("Hello World");
}
else
{
printf("Bad");
}
return 0;
}

This is not working because you are comparing two strings the wrong way. You need to use strcmp. Check this answer to see what strcmp returns in C.
To make your program work, change the line
if (user == 'admin')
to
if (strcmp (user, "admin") == 0)
Also, using scanf might be a bit dangerous, in rare cases. I prefer using fgets for strings. To use fgets, do:
fgets (user, sizeof (user), stdin);

Related

How do I check for a specific character after a user inputed a string? [closed]

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 1 year ago.
Improve this question
I am a new developer to C and I am trying to make a password detector and I am trying to code something that reads the users password and checks if it has a "!" in it. Yet, I cant seem to get it to work. the output of "int special" always equals 0.
The code:
#include <stdio.h>
#include <string.h>
void main() {
// check for special characters
// check for length of password
char password[30];
int length;
int len = 15;
printf("Dear user please enter a password:\n ");
scanf_s("%s", &password, 30);
length = strlen(password);
if (length < len) {
printf("invalid password (password must be 15 - 30 characters)");
exit();
}
int special = 0;
if (strchr(password, "!") != NULL)
{
special = 1;
}
printf("%d", special);
}
The basic idea of the program is correct, but a couple of fixes are needed to make it work and standard compliant:
The typical signature for the main function, using no parameters, is int main(void). See the C standard document for more information.
Include stdlib.h for the exit(..) function. This function needs an argument, and since it is used to exit with failure, the best choice is EXIT_FAILURE as defined in stdlib.h. Since exit(..) is called in the main function, another option is to simply return EXIT_FAILURE.
The scanf_s function is a bit of a special case: __STDC_WANT_LIB_EXT1__ needs to be defined as the integer constant 1 before stdio.h is included. See here for more information. Note that providing an implementation for this function is optional in C, so it is not the best choice for portability. Here, fgets is a better alternative.
The function scanf_s needs a char array to write to and password has exactly that type. Therefore, the "address of" operator (&) shouldn't be used here.
Then function strchr needs a char argument ('!'), not a string literal ("!"). See here for the exact function prototype.
The code will all fixes applied:
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
// check for special characters
// check for length of password
char password[30];
int length;
int len = 15;
printf("Dear user please enter a password:\n");
scanf_s("%s", password, 30);
length = strlen(password);
if (length < len) {
printf("invalid password (password must be 15 - 30 characters)\n");
exit(EXIT_FAILURE);
}
int special = 0;
if (strchr(password, '!') != NULL)
{
special = 1;
}
printf("%d\n", special);
}
A few additional suggestions:
Use a macro for the constant length to give it a name, and to define it once and reuse it multiple times.
Use the size_t type for lengths. This is also the type that is returned by strlen.
Declare variables as close as possible to where these are first used.
Store the result of strchr directly into a boolean value. To use the bool type, include stdbool.h.
The improved code:
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PASSWORD_LENGTH_MAX 30U
int main(void) {
char password[PASSWORD_LENGTH_MAX];
printf("Dear user please enter a password:\n");
scanf_s("%s", password, PASSWORD_LENGTH_MAX);
size_t length_min = 15U;
size_t length = strlen(password);
if (length < length_min) {
printf("Invalid password (password must be 15 - 30 characters)\n");
exit(EXIT_FAILURE);
}
bool contains_special_character = strchr(password, '!');
printf("%d\n", contains_special_character);
}

programm in c (go a round in a room) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a little problem with a C-programm, I wrote. It should be like "you go in a room.. is there a wall? no? then move on.. is there a wall? yes? then turn around" and so on. I am stucked, I go in the room and turn around but do not know how to go further.
#include <stdio.h>
void main()
{
char answer[2];
answer[0] = "Y";
answer[1] = "N";
do
{
printf("Move!\n");
printf("Is there a wall?\n");
scanf("%s",answer);
}
while (answer[0] != 'Y' );
printf("Turn around!");
}
I read about loops and ifs, but my head do not make klick.
Thanks for reading,
hjerteblod
Assuming you want to never exit the game. If so, try this code -
#include <stdio.h>
int main()
{
char answer;
while(1){
printf("Move!\n");
printf("Is there a wall?\n");
scanf(" %c", &answer);
if (answer == 'Y'){
printf("Turn around!\n");
}
}
return 0;
}
"Y" is a string with two characters, answer[0] is a character, you cannot assign a string to a character. So you can change this code like this answer[0] = 'Y'.
By the way, you are better to return an int value in the function main.
include <stdio.h>
int main(){
// your code here
return 0;
}
"N" is a string literal, which evaluates to a pointer to the first element of the string literal "Y" in memory. If you try to assign it to answer[0] you invoke undefined behavior, since you assign a address value to char objects.
The same goes for answer[1] = "N";.
Both assignments, answer[0] = "Y"; and answer[1] = "N"; should have give you a warning, like this from GCC:
warning: assignment to 'char' from 'char *' makes integer from pointer without a cast
Never ignore compiler warnings.
You don't need an array at all, use a single char for answer.
You need an infinite loop for always going further or turning back from a wall, here implemented by while (1).
Note that this is an unfinished algorithm. In a real production program you need a condition to break out of the loop. But just for the sake of your issue, here is want I think you need:
#include <stdio.h>
int main (void)
{
char answer;
while (1)
{
printf("Move!\n");
printf("Is there a wall?\n");
if ( scanf(" %c", &answer ) != 1 )
{
fputs("Error at input!", stderr);
return 1;
}
if ( answer == 'Y' )
{
printf("Turn around!\n");
}
}
}
Side Notes:
Always check the return value of input functions such as scanf() if an error occurred.
void main() is not standard compliant. Use a return type of int and declare the parameter list of type void instead of to leave it empty.
I recommend you to read a good C starting book, f.e. Modern C by Jens Gustedt or The C Programming Language Second Edition by the inventors of C.
For more information about undefined behavior, take a look at this SO question:
Undefined, unspecified and implementation-defined behavior

Program to read input lines of any length in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
And I want it to print to output as is. Curently I am using this code
#include <stdio.h>
#include <ctype.h>
#define BUFFER_SIZE 2000
int main(void)
{
char buffer[BUFFER_SIZE];
while(fgets (buffer, BUFFER_SIZE, stdin) !=NULL)
{
printf("%s",buffer);
}
return 0;
}
Then I want the program to be able to skip html tags in the original text but I don't know exactly how to work around that.
You should use getline(3) (at least on Posix compliant systems). Your fgets based code won't work with very long lines (because a very long line would be "truncated": all of it would be read, but only BUFFER_SIZE characters would have been copied, and the rest of the line ignored).
You could code
char* linebuf=NULL;
size_t linesize=0;
while (!feof(stdin)) {
ssize_t linelen = getline(&linebuf, &linesize, stdin);
if (linelen<0) { perror("getline"); exit(EXIT_FAILURE); };
fputs(linebuf, stdout);
}
In the above code, the linebuf will (unless failure) be grown to the widest line size. You should free(linebuf) after that loop...

using fgets and strcmp in C [duplicate]

This question already has answers here:
strcmp on a line read with fgets
(6 answers)
Closed 9 years ago.
I'm trying to get a string input from the user and then run different functions depending on the input they've entered.
For example, say I asked, "What is your favorite fruit?" and I want the program to comment depending on what they enter...I'm not sure how to do this. Here's what I have so far:
#include <stdio.h>
#include <string.h>
char fruit[100];
main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
if (strcmp(fruit, "apple")) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
}
When I run the program, no matter what I enter, it never does the else statement.
Thanks for your help!
Note two things in your code:
fgets keeps the trailing '\n'. the associated char in fruit should be replaced with a '\0' before comparing with the string "apple".
strcmp return 0 when two strings are the same, so the if clause should be changed based on what you mean.(The fruit and "apple" be equivalent in the if clause)
Standard usage of C main function is int main(){ return 0;}
The revised code:
#include <stdio.h>
#include <string.h>
char fruit[100];
int main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
fruit[strlen(fruit)-1] = '\0';
if (strcmp(fruit, "apple") == 0) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
return 0;
}
Change the if condition to the following:
if(strcmp(fruit,"apple") == 0)
strcmp returns 0 strings if match. You should always compare the result using == operator
strcmp returns 0 if the inputs match, some value>0 if the left is "greater" than the right, some value<0 if the left is "lesser" than the right. So usually you want to simply test for equality with strcmp(...)==0. But there is also the clever version: !strcmp(...). Even if you don't use this style, it's useful to learn to recognize it.
And remember that fgets does not remove the newline character '\n' from the string.

what is the use of %.*s in this program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
static char string[12];
int length,c,d;
printf("Enter a string :");
gets(string);
length=strlen(string);
printf("\nLength of the string is %d",length);
for(c=0;c<=length-2;c++)
{
d=c+1;
printf("\t%.*s\n",d,string);
}
for(c=length;c>=0;c--)
{
d=c+1;
printf("\t%.*s\n",d,string);
}
}
I am very much confused about the usage of %.*s in the printf statement. I know %s is used for displaying strings, but I am confused the usage of .* before s in this program. Also there is only one datatype (%s) mentioned inside the quotation marks in the printf statement, but there are two variables mentioned in the printf statement.
It is a precision component, which specifies maximum number of bytes for string conversions. Asterisk (*), uses an integer argument, which specifies the value (for precision) to be used.
As an example, the following code:
#include <stdio.h>
int main(int argv, char **argc)
{
char *s = "hello, world";
printf("%.*s\n", 4, s);
return 0;
}
gives output:
hell
The format statement can allow a width and precision value. So, to print a string for a variable length then specify printf("%.*s", length, string). The length is substituted for the asterisk.

Resources