This question already has answers here:
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 8 years ago.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main()
{
bool flag= true;
int menu_option;
char first_band [16], second_band [16], third_band [16], fourth_band [16], green[16];
while (flag)
{
printf("Please choose an option:\n");
printf("To run the program, enter 1.\n");
printf("For help, enter 2.\n");
printf("To exit, enter 3.\n");
scanf("%i", &menu_option);
switch (menu_option)
{
case 1:
printf("Please enter the colour of the first band on the resistor:\n");
scanf(" %s", first_band);
printf("Please enter the colour of the second band on the resistor:\n");
scanf(" %s", second_band);
printf("Please enter the colour of the third band on the resistor:\n");
scanf(" %s", third_band);
printf("Please enter the colour to fourth band ont he resistor. If there is no fourth band, enter 'null'.\n");
scanf(" %s", fourth_band);
flag=false;
break;
case 2:
flag=true;
printf("program instructions");
break;
case 3:
flag=false;
return 0;
break;
default:
flag=true;
printf("Invalid command.\n");
break;
}
}
printf("%s", first_band);
if (first_band == "green")
printf("the first band is %c\n", first_band);
return (0);
}
So i can't get the last "if" statement to print "the first band is %s". the print statement right above it is to see if the program is even reading the user input...which it seems to be. It just won't seem to recognize the word and execute the if statement. I feel like my syntax is wrong when dealing with the char strings, which is causing this problem, but I'm new to this so a helping hand would be much appreciated.
You have to use strcmp() instead.
if (strcmp(first_band, "green") == 0)
printf("the first band is %c\n", first_band);
Related
Im having some problems making my newly started project to work (also im a beginner).
For some reason option number 4 in my interactive menu doesn't work and just takes a default route (doesn't output whats inside a file (file directory is fine.).
At this point i've read every forum searching for answer but couldn't modify my code in any way that would work.
So I decided to ask you for help.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define kFileLocation "/Users/patrykpiwowarczyk/Desktop/STUDIA/FoCP/Kodowanie/TestProjektSemestralnyAngielski/TestProjektSemestralnyAngielski/authors.txt"
void options();
void start(void);
void score(void);
void optionz(void);
void author(void);
void pexit(void);
int main(void)
{
char ch;
int num;
char option;
while (1) {
printf("****Your English Learning Index Cards****\n\n");
printf("Enter 1-5 of the following options: \n\n");
options();
scanf("%c", &option);
switch (option) {
case '1':
break;
case '2':
break;
case '3':
break;
case '4':
author();
break;
case '5':
pexit();
break;
default:
printf("Please insert number ranging from 1-5 though... No cheating! \n\n");
printf("Press ENTER key to Continue\n");
}
}
return 0;
}
void options()
{
printf("1. Start Game \n");
printf("2. View Scoreboard \n");
printf("3. Options \n");
printf("4. Author \n");
printf("5. Exit \n\n");
}
void author()
{
char c;
FILE *authorsFile;
if ((authorsFile = fopen("/Users/patrykpiwowarczyk/Desktop/STUDIA/FoCP/Kodowanie/TestProjektSemestralnyAngielski/TestProjektSemestralnyAngielski/authors.txt","r")) == NULL)
{
printf("FAILED to read the file, maybe check directory?\n");
exit(1);
}
while ((c = fgetc(authorsFile)) != EOF)
{
printf("%c", c);
}
fclose(authorsFile);
}
void pexit()
{
puts("Your progress has been saved, see you next time.");
exit(0);
}
if you could help me in any way I would appreciate it soo much..
Greetings, Patryk Piwowarczyk.
PS: the #define kFileLocation is a leftover from my other tries. Omit it.
Based on your comments, I conclude the following:
The problem was that scanf correctly wrote the digit into the variable option the first time it was called. However, the second time scanf was called, it immediately returned the newline character from the previous menu selection, instead of waiting for the user to enter another digit. Whenever scanf returned a newline, the default case was triggered.
Therefore, the problem can be best solved by changing the scanf call to the following:
scanf(" %c", &option);
By adding a space to the start of the format string, you instruct scanf to discard all whitespace characters before reading the character. That way, you can insure that a newline will never be written into the option variable.
The problem of scanf reading newline characters instead of discarding them has been discussed in more detail in this question.
I want to create an edit function that receives as a parameter by reference the vector of songs. (using pointers)
The user must choose the song number and re-enter the data of that position of the vector.
I created the struct, I am already receiving the values and I am playing. But I do not know how to edit. Anyone to help me start this part?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>
#include <string.h>
struct registry_of_music {
char name[50];
char artist[60];
char url[80];
};
struct registry_of_music music[9];
int main() {
int i;
printf("\nRegistry of Music\n\n\n");
for(i = 0; i <= 3;i++ ){
printf("Name of Music: ");
fflush(stdin);
fgets(music[i].name, 50, stdin);
printf("Name of Artist: ");
fflush(stdin);
fgets(music[i].artist, 60, stdin);
printf("URL of Internet: ");
fflush(stdin);
fgets(music[i].url, 80, stdin);
}
int op;
do
{
printf("1 - Play\n");
printf("2 - Edit\n");
printf("3 - Exit\n");
printf("Please enter a value:");
scanf("%d", &op);
switch(op) {
case 1: play();
break;
case 2: edit();
break;
case 3: printf("Bye\n");
break;
default: printf("Try Again\n");
}
} while (op!=3);
getch();
return(0);
}
void play(){
int i;
for(i = 0; i <= 3;i++ ){
printf("Name ...........: %s", music[i].name);
printf("Artist .....: %s", music[i].artist);
printf("URL .....: %s", music[i].url);
}
}
void edit(){}
The «fill instance of structure» action is absolutely identical if performing on uninitialized structure or initialized. Even if an instance is not initialized, it has some rubbish values in its fields.
On the other hand there is no way to specify default value which will be shown in fgets's prompt and will be available for keyboard edit, unless you're using much more complicated (and NOT included in ISO C standard) tools.
I'm making a menu that lists options 1-3. The user is expected to enter an integer.
scanf("%d", &select_option)
How do I prompt error when user enters a char (for example "a", or "asd" for long strings, or a mixture like "1a2") instead of an expected int? Thanks.
Note: When the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason.
Here's my program (minimal example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
while(select_option != 4)
{
switch(select_option)
{
case 1:
printf("You like tennis! Nice! \n");
break;
case 2:
printf("You like badminton! Nice!");
break;
case 3:
printf("You like basketball! Nice!");
break;
default:
system("clear");
printf("Invalid option. Please re-enter your choice (1-4).\n");
}//end switch
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
}//end while
}//end main
You could do this:
#include <stdio.h>
int main(void) {
int v;
int ret = scanf("%d", &v);
if(ret == 1)
printf("OK, %d\n", v);
else
printf("Something went wrong!\n");
return 0;
}
where I took advantage of the return value of scanf(), and based on that value, I made an assumption. This will fail for the case of "1a2", but will succeed for "12" and "a".
However, this is a broad question and personally the way I would go for it is:
Use fgets() to read input.
Discard newline.
Convert string to integer (with strtol() for example).
Validate input.
I am assuming u are a beginner. You can use Switch Case which is used usually for creating menus and depending on the choice of the user executes the particular case.
I will show u a small example.
#include<stdio.h>
#include<conio.h>
int main()
{
int n;
printf("Select the sports u want to do\n");
printf("1.Tennis\n2.Karate\n3.Football\n");
scanf("%d",&n);
Switch(n)
{
case 1:printf("You chose Tennis\n");
break; //To prevent from all cases being executed we use
//break which helps from coming out of a loop
case 2:printf("You chose Karate\n");
break;
case 3:printf("You chose Football\n");
break;
default:printf("Please enter an appropriate number !");
//Cases which dont match with the input are handled by default !
}
}
Also to make the user enter input until he wants to exit add a while loop with a variable !
I hope this helps!
I am new in this world of programming. I am learning programming at my school. My teacher recently ask the class to create a menu with limited selection that will end with a sentinel value.
So here's my coding:
#include <stdio.h>
void menu(void);
void choice1();
void choice2();
void choice3();
char choice;
int main() {
do {
menu();
if (choice =='1')
choice1();
else if (choice =='2')
choice2();
else if (choice =='3')
choice3();
else if (choice =='4')
break;
else
printf("Invalid character.");
} while (choice != '4');
return 0;
}
void menu(void) {
printf("\nMenu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("3) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
scanf("%c", &choice);
}
void choice1() {
printf("\nChoice 1\n");
}
void choice2() {
printf("\nChoice 2\n");
}
void choice3() {
printf("\nChoice 3\n");
}
When I try to run it, by putting the number 1, 2, 3, the output came out but after that the function menu() and also the line "Invalid character." came out. As for as the other character, the menu() and the "Invalid character" came out twice. Number 4 does end the program. Is there any improvement that I can make to make sure the menu() and the line "Invalid character." does not come out unnecessarily?
In line-buffered input, the newline character lingers in the buffer after you read a single character for 'choice' and hence you get Invalid character. unintentionally.
You are required clear the buffer after reading the choice
scanf("%c", &choice);
while(getchar()!='\n')
/* Wasting the buffer
* Hence ensuring that the character you enter
* is indeed considered for 'choice'
*/
;; // Do nothing in particular
As a side note, your program looks like a typical use-case for the switch-case command and maybe your teacher expects you to use it.
Considering the scenario mentioned by #chqrlie in [ this ] comment, the workaround is to add after
scanf("%c", &choice);
the below lines
int c;
while ((c = getchar()) != EOF && c != '\n')
;; //Wasting the buffer
The problem is simple: the terminal is line buffered: you must press enter for the input to become available to your program, the first scanf("%c", &choice) retrieves the character typed and the second call retrieves the linefeed ('\n') that was generated by the enter key.
There are multiple ways to avoid this problem. You can add a space in the scanf format before the %c: scanf(" %c", &choice); or you can read characters after the first until you get a '\n'.
Note that you must check the return value of scanf to avoid undefined behavior if the user enters an end of file. It is also advisable to avoid global variables: the function menu() should return the choice specified. Using a switch statement is also more idiomatic for this.
Here is a corrected version:
#include <stdio.h>
int menu(void);
void choice1(void);
void choice2(void);
void choice3(void);
int main(void) {
int ch;
for (;;) {
switch (ch = menu()) {
case '1': choice1(); continue;
case '2': choice2(); continue;
case '3': choice3(); continue;
case '4':
case EOF: break;
default: printf("Invalid character %c\n", ch); continue;
}
break;
}
return 0;
}
int menu(void) {
char choice;
printf("\nMenu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("3) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
if (scanf(" %c", &choice) == 1)
return choice;
else
return EOF;
}
void choice1(void) {
printf("\nChoice 1\n");
}
void choice2(void) {
printf("\nChoice 2\n");
}
void choice3(void) {
printf("\nChoice 3\n");
}
As already mentioned in other answers the problem is the newline character.
When you press 1 followed by enter, you'll get two chars, i.e. 1 and \n. So your loop runs twice and prints Invalid character when \n is processed.
Here is an alternative solution for your problem. Just add a space before %c.
scanf(" %c", &choice);
This works because the space will match any number of white-space characters and thereby match the \n and remove it.
From the man page:
A sequence of white-space characters (space, tab, newline,
etc.......). This directive matches any amount of
white space, including none, in the input.
Additional comments
You should always check the value returned by scanf to make sure you read the correct number of values.
if (scanf(" %c", &choice) != 1)
{
// Add error handling ....
// For instance you could terminate the program like
exit(1);
}
In your program choice is a global variable. In general global variables should be avoid if possible. In your case you could make choice a local variable in main and let menu return a char. Like:
// char choice; Remove global variable
int main() {
char choice; // Add local variable
do {
choice = menu(); // Assign to local variable
.....
}
char menu(void) { // Make the function return a char
char choice; // Add local variable
printf("\nMenu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("3) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
if (scanf("%c", &choice) != 1) exit(1); // Assign to local variable
// On failure -> exit
return choice; // Return value of local variable
}
You can write scanf(" %c",&choice); (with whitespace) instead of scanf("%c",&choice);
When I try to run it, by putting the number 1, 2, 3, the output came
out but after that the function menu() and also the line "Invalid
character." came out.
It's happening because of the new line character you press after each number. It's itself a character and loop is iterated one more time for this. As it is an invalid character, that's why "Invalid character." is showing.
Try using getchar() after scanf().
Edit: fixed my previous while loop which may exit incorrectedly:
#include <stdio.h>
int main() {
int choice;
printf("Menu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("2) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
while (1) {
char c = scanf("%d",&choice);
if (c == EOF || choice == 4) break;
if (choice == 1 || choice == 2 || choice == 3) {
printf("Choice %d.\n", choice);
} else {
printf("Invalid character.\n");
}
}
return 0;
}
You can use function if you want, but not necessary in this case. You need to understand how many times your loop actually runs and compare it to that you expect.
My previous code:
#include <stdio.h>
int main() {
int choice;
printf("Menu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("2) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
while (scanf("%d", &choice) && choice != 4) {
if (choice == 1 || choice == 2 || choice == 3) {
printf("Choice %d.\n", choice);
} else {
printf("Invalid character.\n");
}
}
return 0;
}
I am trying to create a menu and my menu is listed a-d. I want the if statement to read a for first item in menu all the way to do but my program keeps crashing. How can I fix this?
#include <stdio.h>
#include <string.h>
int main()
{
char option[4];
system("cls");
printf("+++++++++++++++++++++++++++++++++++++>>>ATHLETE DATA MANAGEMENT SYSTEM<<<++++++++++++++++++++++++++++++++++++++\n\n");
printf("\t\t\t\t\ta\. Enter Athlete Data\n");
printf("\t\t\t\t\tb\. Determine Distance to Reach World Record\n");
printf("\t\t\t\t\tc\. Display Athlete Management Report\n");
printf("\t\t\t\t\td\. Exit\n");
printf("Type the corresponding letter (a-d) to access the menu. ");
scanf("%d", &option);
if(strcmp(option, "a")==0){
printf("Welcome to Athlete Data Page\n");
}
else if(strcmp(option,"b")==0){
printf("Determine Distance to Reach World Record\n");
}else if(strcmp(option, "c")==0){
printf("Athlete Management Report");
}else if (strcmp(option, "d")==0){
printf("Exit Menu");
printf("Press Y for yes and N for no");
}
else{
printf("Incorrect code entered.");
}
return 0;
}
You are using a C-style string variable (an array of characters) char option[4];, but reading it as a decimal integer using the %d in scanf. You would want the %s option to do that.
http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm