How can I end the program when a user enters "quit"? I tried an if statement before the loop and within the loop. I'm pretty new to programming and it's bothering me that I can't figure this out. I even tried a do while loop and that didn't work at all.
int main()
{
char word[30];
char yn;
int loopcount;
yn=0;
loopcount=0;
printf("Enter a word:");
scanf(" %s", word);
printf("Would you like to change the word? y=yes, n=no \n");
scanf(" %c", &yn);
if (yn=='n')
{
return 0;
}
while(yn>0)
{
printf("Enter a new word: \n");
scanf(" %s", word);
printf("New word is: %s \n");
loopcount= loopcount+1;
printf("You have changed the word %d times.\n", loopcount);
printf("Would you like to change the word? y=yes, n=no\n");
scanf(" %c", &yn);
if (yn=='n')
{
return 0;
}
return 0;
}
return 0;
}
Use strcmp()
scanf(" %s", word);
if (strcmp(word, "quit") == 0) {
return 0;
}
Related
May I need help in sorting this out? Basically, I'm tasked to play around with ctype header files. I get input from the user and then I give the output depending on the input provided.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char savedPassword[] = "123456";
char username[100], password[100], charInput, decision;
printf("Username: ");
fgets(username, sizeof(username)/sizeof(username[0]), stdin);
printf("Password: ");
scanf(" %s", &password);
if (strcmp(savedPassword, password) == 0)
{
printf("Welcome, %s\n", username);
do
{
printf("Enter any character: ");
scanf(" %c", &charInput);
if(isalpha(charInput))
{
if(isupper(charInput))
{
printf("%c is a capital letter.\n", charInput);
} else {
printf("%c is a small letter.\n", charInput);
}
} else if (isdigit(charInput))
{
printf("%c is a digit.\n", charInput);
} else if (ispunct(charInput))
{
printf("%c is a punctuation.\n", charInput);
} else if (isspace(charInput))
{
printf("%c is a space.\n", charInput);
}
printf("Do you want to exit (Y/N)? ");
scanf(" %c", &decision);
if (toupper(decision) != 'Y' && toupper(decision) != 'N')
{
printf("Please re-enter the correct response.\n");
printf("Do you want to exit (Y/N)? ");
scanf(" %c", &decision);
}
}while(toupper(decision) != 'Y');
printf("Thank you for using the app!");
} else {
printf("Wrong password! Try again!");
}
return 0;
}
I couldn't make isspace() work because it seems like scanf() doesn't detect the whitespace anymore as I have used one before the placeholder.
Thank you!
i tried to make a calculator but could the compiler is checking my if conditions properly.
here is my code,
i could not figure out how to solve this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("to add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c",&mode);
printf("%d %d %s \n",first,sec,mode);
if (mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == "s")
{
printf("%d \n",first-sec);
}
else if (mode == "m")
{
printf("%d \n",first*sec);
}
else if (mode == "d")
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
void def(char name[],int age)
{
printf("het ur a %s and yo age is %i \n",name,age);
}
first attempt tried using a string instead of character (failed )
second attempt tried using a character but failed though!!
For comparing a single character in c, you must use single quotes. Consider an array of characters array[4] = {'c','a','r','\0'};
if(array[0] == 'c'){
//...
}
Comparing with double quotes, make the value inside it a string. For comparing strings you should #include <strings.h> and use the strcmp function.
There are two problems
mode == "s" mode is a char so just use mode == 's' and do the same for others also.
printf("%d %d %s \n",first,sec,mode); should be printf("%d %d %c \n",first,sec,mode);
you are using %s for printing a char
In your code "s" is a string not a caracter,to get a caracter you should write like this: 's'
here is the correction of your code :
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("\nMenu : \n");
printf("\nto add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c", &mode);
printf("%d %d %c \n",first,sec,mode);
if(mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == 's')
{
printf("%d \n",first-sec);
}
else if (mode == 'm')
{
printf("%d \n",first*sec);
}
else if (mode == 'd')
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
I am having problem with appending more records to this file. It allows me add just one record but I cannot add more than one record. And cannot figure out what is going wrong with it?
void new_customer()
{
char ch;
int flag=0;
FILE *fp;
fp=fopen("DataFile.txt", "a+");
printf("Enter today's date (dd/mm/yyyy) : ");
scanf(" %d/%d/%d", &add.deposit.day, &add.deposit.month, &add.deposit.year);
printf("Enter Account Number : ");
fflush(stdin);
scanf("%ld", &check.account_number);
while(fscanf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c", &add.account_number, add.customer_name, add.father_name, add.address, add.Nationality, &add.p_number, &add.age, &add.dob.day, &add.dob.month, &add.dob.year, &add.amount, &add.deposit.day, &add.deposit.month, &add.deposit.year, &add.account_type)!=EOF)
{
if(check.account_number==add.account_number)
{
printf("Account number already taken. Please contact administrator.\nPress enter to continue.");
getch();
system("cls");
main();
}
}
add.account_number=check.account_number;
printf("Enter name : ");
fflush(stdin);
gets(add.customer_name);
printf("Enter Father's name : ");
fflush(stdin);
gets(add.father_name);
printf("Enter your age : ");
fflush(stdin);
scanf("%d", &add.age);
printf("Enter Date of birth (dd/mm/yyyy) : ");
scanf("%d/%d/%d", &add.dob.day, &add.dob.month, &add.dob.year);
printf("Enter Phone Number : ");
fflush(stdin);
gets(add.p_number);
printf("Enter Nationality : ");
fflush(stdin);
gets(add.Nationality);
printf("Enter Address : ");
fflush(stdin);
gets(add.address);
printf("Enter Account Type:\nPress S for Savings, \nPress C for Current, \nF for Fixed : ");
fflush(stdin);
scanf("%c",&add.account_type);
while(flag!=1)
{
if (add.account_type=='S'|| add.account_type=='s'||add.account_type=='C'||add.account_type=='c'||add.account_type=='F'||add.account_type=='f')
{
flag=1;
}
else
{
printf("\nWrong Input. Input Again : ");
fflush(stdin);
scanf("%c", &add.account_type);
flag=0;
}
}
printf("Deposit Amount : ");
fflush(stdin);
scanf("%d", &add.amount);
fprintf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c\n", add.account_number, add.customer_name, add.father_name, add.address, add.Nationality, add.p_number, add.age, add.dob.day, add.dob.month, add.dob.year, add.amount, add.deposit.day, add.deposit.month, add.deposit.year, add.account_type);
printf("\nAccount Created Successfully!!\n");
fclose(fp);
while(1)
{
printf("Return to Main Menu? Y/N : ");
fflush(stdin);
scanf("%c", &ch);
if(ch=='Y' || ch=='y')
{
system("cls");
main();
}
else if(ch=='N' || ch=='n')
{
exit(0);
}
else
{
printf("\nWrong input. Try Again!\n");
}
}
}
This is just a function to a big program. I am attaching just the part which includes file handling. If you want I can attach more code.
Here I am adding the main driver code
#include<windows.h>
#include<stdio.h>
#include<stdlib.h>
#include "E:\Projects\C Language\Bank-Management-System\File Containing Functions.c"
int menu(void);
int gotoxy(int x, int y)
{
COORD c;
c.X=x;
c.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
int menu()
{
int i, a;
gotoxy(40,0);
printf("BANK MANAGEMENT SYSTEM\n");
gotoxy(43, 3);
printf(":: MAIN MENU ::\n");
gotoxy(40, 5);
printf("[1] Create a new account");
gotoxy(40, 6);
printf("[2] Update information of existing account");
gotoxy(40, 7);
printf("[3] Transactions");
gotoxy(40, 8);
printf("[4] Check details of existing account");
gotoxy(40, 9);
printf("[5] Remove existing account");
gotoxy(40, 10);
printf("[6] View Customer List");
gotoxy(40, 11);
printf("[7] Exit\n");
gotoxy(40, 15);
printf("Enter your choice : ");
scanf("%d", &a);
return a;
}
int main()
{
int choice;
choice=menu();
switch(choice)
{
case 1:
{
system("cls");
new_customer();
break;
}
case 3:
{
system("cls");
transaction();
break;
}
case 7 :
{
system("cls");
printf("Thank You for using our services!!");
exit(0);
}
default:
{
printf("Wrong Input!!\n");
getch();
system("cls");
menu();
}
}
getch();
return 0;
}
Link to see input : https://pasteboard.co/Jt3xWrP.jpg
Here is the file after first input : https://pasteboard.co/Jt3yYA9.jpg
Another input :https://pasteboard.co/Jt3yHSC.jpg (this is where it gets stuck forever and doesn't let me add another record)
Text stored inside file :
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
So to start with the file holds:
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
And you try to scan it with
fscanf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c"
That is:
1 number
5 strings
1 number
...
As you can see, the file doesn't match that.
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^
ok ok ok ok ok ok Not ok, so stop here
The next fscanf will not match anything (it expects a number but the file has "Road") so nothing is read.
In other words, you are stuck in the while forever.
I'll recommend reading the file in a line by line manner using fgets.
Then you can (in principle) use sscanf afterwards. But notice that %s reads a single word and your code allow multiple words for a single entry! In other words - your file can't be parsed using %s.
So consider another file format. For instance, you could use 1 line for each item in a record. That will make parsing much easier.
Hey guys im learning C and i started programming a Hangman Game. That should be played over 1 word and i choosed "informatik".
What i want to do is asking for users name and then start.
#include<stdio.h>
int main() {
int correct = 0;
int mistake = 0;
int number = 0;
char name[20];
char Word[]={'i','n','f','o','r','m','a','t','i','k'};
char guessStatus[]={'_','_','_','_','_','_','_','_','_','_','\0'};
char guess;
printf("##### Welcome to Hangman #####\nWhat is your Name?\n");
scanf(" %s", name);
fflush(stdin);
printf("Hello %s!\n", name);
while (mistake <=10 && number<10) {
printf("Guess a letter: ");
guess = getchar();
printf("%c", guess);
correct = 0;
for (int search=0; search<10; search++)
{
if (guess == Word[search]){
number++;
guessStatus[search] = Word[search];
correct = 1;
}
}
if (correct == 0){
mistake++;
printf("%c is wrong!\nYour Status is: %s\nYou have %i tries left\n", guess,guessStatus,10-mistake);
}
else {
printf("Good job %s!\nYour Status is: %s\nYou have %i tries left\n", name,guessStatus,10-mistake);
}
}
}
Problem is when i run the code and enter any letter, program counts "enter" also as a letter.I used fflush(stdin) as a hope even i don't know anything about it but didn't work :)
Problem output like:
Welcome to Hangman
What is your Name?
john
Hello john!
Guess a letter:
is wrong!
Your Status is: __________
You have 9 tries left
Guess a letter: i
iGood job john!
Your Status is: i_______i_
You have 9 tries left
Guess a letter:
is wrong!
Your Status is: i_______i_
You have 8 tries left
I don't know how to deal with it.Help would be very appreciated.
Add the gethcar(); will be ok for read the \n:
#include <stdio.h>
int main() {
int correct = 0;
int mistake = 0;
int number = 0;
char name[20];
char Word[]={'i','n','f','o','r','m','a','t','i','k'};
char guessStatus[]={'_','_','_','_','_','_','_','_','_','_','\0'};
char guess;
printf("##### Welcome to Hangman #####\nWhat is your Name?\n");
scanf(" %s", name);
getchar(); // add this line
printf("Hello %s!\n", name);
while (mistake <=10 && number<10) {
printf("Guess a letter: ");
guess = getchar();
printf("%c", guess);
correct = 0;
for (int search=0; search<10; search++)
{
if (guess == Word[search]){
number++;
guessStatus[search] = Word[search];
correct = 1;
}
}
if (correct == 0){
mistake++;
printf("%c is wrong!\nYour Status is: %s\nYou have %i tries left\n", guess,guessStatus,10-mistake);
}
else {
printf("Good job %s!\nYour Status is: %s\nYou have %i tries left\n", name,guessStatus,10-mistake);
}
}
}
try this it should work
Use
scanf(" %c",&guess);
instead of
guess = getchar(); //remove this line
printf("%c", guess); //remove this line also
I have a scanf that doesn't accept input. The value is automatically zero, even if the variable wasn't initialized. The scanf is skipped:
printf("\nEnter the number of the student to be dropped: ");
fflush(stdin);
scanf(" %d ",&choice);
printf("choice is %d", choice);
When the program is run, it immediately displays "choice is 0".
The snippet above is taken from the drop() function in this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student{
char name[50];
char* course;
};
main()
{
char repeat;
do{
system("cls");
int mainchoice;
printf("Student Enrollment System");
printf("\n");
printf("\n");
printf("1. View\n");
printf("2. Enroll\n");
printf("3. Drop enrollment\n");
printf("Select choice: ");
fflush(stdin);
scanf("%d",&mainchoice);
system("cls");
switch(mainchoice){
case 1:
view();
break;
case 2:
enroll();
break;
case 3:
drop();
break;
default:
printf("Please enter a valid number.");
getch();
fflush(stdin);
break;
}
printf("\nWould you like to make another transaction? [Y/N]: ");
fflush(stdin);
scanf("%c",&repeat);
}while(repeat=='Y'||repeat=='y');
}
view(){
int ctr = count();
printf("Enrolled Students:\n\n");
system("type records.txt");
printf("\n\nNumber of students enrolled: %d", ctr);
getch();
fflush(stdin);
}
enroll(){
int choice;
char validate;
printf("1. Information Technology\n");
printf("2. Computer Science\n");
printf("3. Computer Engineering\n");
printf("4. Information Systems\n");
struct student news;
printf("Name: ");
fflush(stdin);
gets(news.name);
printf("Course Number: ");
fflush(stdin);
scanf("%d", &choice);
switch(choice){
case 1:
news.course = "BSIT";
break;
case 2:
news.course= "BSCS";
break;
case 3:
news.course = "BSCpE";
break;
case 4:
news.course = "BSIS";
break;
default:
printf("Please enter a valid number\n");
break;
}
printf("Enroll %s to %s? [Y/N]:",news.name,news.course);
fflush(stdin);
scanf("%c", &choice);
if(choice=='Y' || choice=='y')
{
FILE * records;
records = fopen("records.txt", "a+");
fprintf(records, "%s, %s\n",news.name,news.course);
fclose(records);
printf("%s has been enrolled to %s\n",news.name, news.course);
}
else
{
printf("You have chosen to cancel your transaction");
}
}
drop(){
printf("Drop Student:\n\n");
int ctr = 0;
int choice; //which student to delete
char c;
FILE * record; // original records.txt
FILE* repo; //temporary data storage
record = freopen("records.txt", "r", stdin);
while((c = fgetchar())!=EOF){
if(c == '\n'){
}
else{
ctr=ctr+1;
printf("%d. ", ctr);
while(1){
printf("%c",c);
c= fgetchar();
if(c=='\n'){
printf("%c",c);
break;
}
}
}
}
fclose(record);
fflush(stdin);
fflush(stdin);
printf("\nEnter the number of the student to be dropped: ");
fflush(stdin);
scanf(" %d ",&choice);
getch();
getch();
fflush(stdin);
ctr = 1;
fflush(stdin);
repo = fopen("temp.txt","w");
record = freopen("records.txt","r",stdin);
while((c = getchar()) != EOF){
if(c == '\n'){
}
else{
while(ctr!=choice){
fprintf(repo,"%c",c);
c= fgetchar();
if(c=='\n'){
fprintf(repo,"%c",c);
ctr = ctr + 1;
break;
}
}
}
}
fclose(record);
fclose(repo);
getch();
}
//counts the number of rows in the record
int count(){
int ctr=0;
char c;
FILE * records;
records = freopen("records.txt","r", stdin);
if(records!=NULL){
while((c=fgetchar()) !=EOF){
if(c=='\n'){
ctr = ctr+1;
}
}
}
fclose(records);
return ctr;
}
Doing fflush doesn't seem to help. Any ideas?
The behavior of fflush is not defined for input streams; fflush(stdin) is a coding error, and you should remove those calls from your code.
When scanning for individual characters, add a blank space before the %c conversion specifier; this will tell scanf to skip any leading whitespace and read the next non-whitespace character:
scanf(" %c", &choice);
The %d and %s conversion specifiers will skip over any leading whitespace.
Edit
Implicit typing is no longer supported as of C99, and it's a bad habit to get into. Explicitly type your functions, and use void as the parameter list to specify that they take no arguments:
main() => int main(void)
view() => void view(void) // void since it isn't returning a value
drop() => void drop(void)
etc.
Similarly, gets was deprecated in C99 and is gone completely as of the 2011 standard. Using it will introduce a point of failure / major security hole in your program. Use fgets instead.