I'm quite new to C programming and I have an issue with how the code prompts the input. I need the inputs under the input statement to come one by one.
Now the way the prompts are output is:
To add a new task enter the details below
Name of Task: Science
Then all the other inputs come as a group
Category of Task:
Information about task:
Due Date of Task:
Status of Task
TD = To-Do
IP = In Progress
CT = Completed Task
Enter Status:
But I want to it ask for the name of the task first and once I input that information, it should ask the category
For example:
To add a new task enter the details below
Name of Task:
This is my code:
#include<stdio.h>
int main() {
char main_choice;
printf("Welcome to your Task Management System\n");
printf("What would you like to do today?\n A: Add New Task\n B: View Task \n C: Manage Tasks\n");
printf("\nEnter your choice:");
scanf("%c", &main_choice);
if (main_choice == 'A'){
char name;
char category;
char info;
char date;
char status;
printf("\nTo Add a new task enter the details below\n");
printf("Name of Task:");
scanf(" %c", &name);
printf("\nCategory of Task:");
scanf(" %c", &category);
printf("Information about task:");
scanf(" %c", &info);
printf("Due Date of Task:");
scanf(" %c", &date);
printf("Status of Task\nTD = To-Do\nIP = In Progress\nCT = Completed Task\n Enter Status:");
scanf(" %c", &status);
}
return 0;
}
When using scanf in C you should put a whitespace before the %c like this:
scanf(" %c", &name);
It is required to put space before %c to skip the white space in buffer memory.
so that %c matches the character given instead of the space char.
Related
I'm writing a program for an employee database and I'm writing the function to add an employee. I'm getting a bus error after my final prompt to scan in info. I'm pretty sure its to do with my scanf statement as I have a print statement right after that is not printing. Why would I be getting this error?
The prompt in question is for reading in job title.
void addEmployee(void)
{
char *name;
char gender;
int age;
char *title;
printf("Enter name: \n");
scanf(" %100s", name);
scanf("%*[^\n]%*c");
printf("Enter gender: \n");
scanf(" %1c", &gender);
scanf("%*[^\n]%*c");
printf("Enter age: \n");
scanf(" %d", &age);
scanf("%*[^\n]%*c");
printf("Enter job title: \n");
scanf(" %100s", title);
scanf("%*[^\n]%*c");
printf("Test");
printf("The employee you've entered is: %s %c %d %s \n", name, gender, age, title);
Employee newEmp = {*name, gender, age, *title};
if(employeeList[0] == NULL)
{
employeeList[0] = &newEmp;
nodeCount++;
}
}
Code is passing in an uninitialized pointer.
char *name; // Pointer 'name' not initialize yet.
printf("Enter name: \n");
// 'name' passed to scanf() is garbage.
scanf(" %100s", name);
Instead, pass a pointer to an existing array
char name[100 + 1];
printf("Enter name: \n");
// Here the array 'name' coverts to the address of the first element of the array.
// scanf receives a valid pointer.
scanf("%100s", name);
This is a mini project for library management system. The problem is that first fgets function for user input in case 1 falls through no matter the content but that of the subsequent ones works. I want to accept the full name of the book name and the author which contains whitespaces from the console.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
// Structure definition
struct library
{
char bookName[50];
char authorName[50];
int numberOfPages;
float price;
};
int main()
{
// Structure Variable declaration
struct library lib[50];
// Variables initialization
int i,j,keepcount;
i=j=keepcount = 0;
// Character arrays
char arth_nm[50],book_nm[50];
while(j!=7)
{
// Menu Selection
printf("\n\n1. Add book information\n2. Display book information\n");
printf("3. List all books of given author\n");
printf("4. List the title of specified book\n");
printf("5. List the count of books in the library\n");
printf("6. Display Highest Price Book\n");
printf("7. Exit");
printf ("\n\nSelect one of the above: \n");
scanf("%d",&j);
switch(j)
{
// Entering book details
case 1:
printf ("Enter book name: ");
fgets(lib[i].bookName, sizeof(lib[i].bookName), stdin);
printf ("Enter author name: ");
fgets(lib[i].authorName, sizeof(lib[i].authorName), stdin);
printf ("Enter pages: ");
scanf ("%d",&lib[i].numberOfPages);
printf ("Enter price: ");
scanf ("%f",&lib[i].price);
keepcount++;
break;
// All book details entered
case 2:
printf("You have entered the following information\n");
for(i=0; i<keepcount; i++)
{
printf ("Book name = %s",lib[i].bookName);
printf ("\tAuthor name = %s",lib[i].authorName);
printf ("\tPages = %d",lib[i].numberOfPages);
printf ("\tPrice = %f",lib[i].price);
printf("\n");
}
break;
// Searching for book details by using the name of the Author
case 3:
printf ("Enter author name : ");
scanf ("%s",arth_nm);
for (i=0; i<keepcount; i++)
{
if (strcmp(arth_nm, lib[i].authorName) == 0)
printf ("%s %s %d %f",lib[i].bookName,lib[i].authorName,lib[i].numberOfPages,lib[i].price);
}
break;
// Searching for book details by using the name of the book
case 4:
printf ("Enter book name : ");
scanf ("%s",book_nm);
for (i=0; i<keepcount; i++)
{
if (strcmp(book_nm, lib[i].bookName) == 0)
printf ("%s \t %s \t %d \t %f",lib[i].bookName,lib[i].authorName,lib[i].numberOfPages,lib[i].price);
}
break;
// Case for Total many of books shelved
case 5:
printf("\n No of books in library : %d", keepcount);
break;
// Case for Highest paid book
case 6:
printf ("Highest Price Book : ");
float temp = 0;
for (i=0;i<keepcount;i++)
{
if(temp < lib[i].price)
temp = lib[i].price;
}
printf("%f", temp);
break;
case 7:
exit (0);
}
}
return 0;
}
Use the fgets() statement for accepting whitespaces:
fgets(arth_nm, 50, stdin);
You should fflush(stdout) it to clear the output buffer like this:
fflush(stdout);
fgets(arth_nm, 50, stdin);
It'll help you to fix this.
yes , there is, as #Rohan Bari said, you can use fgets() , though some compilers does not supports the use of this function. Alternatively, you can use
scanf ("%[^\n]%*c", variableName);
this function takes the input till a new line or enter is pressed, i.e, it will read any character including whitesapces.i hope i've been able to help.
I'm trying to understand the whole concept of pointers, structures, etc so I've created a program that gets user input for two different books and then swaps the info of the two books. I had no trouble doing that, however, a problem arose- when I pressed enter the name of the book would be plain blank and at the output I would, of course, see a blank space. My problem is, how am I able to limit the user to input any letter (A-Z, a-z) and not blank space?
A string of characters when input to an array, they get saved in consecutive memory addresses. We also know that 'NULL' is represented as '\0' in arrays.
With the above things in mind, I performed multiple tests in which, ALL of them failed to yield the desired results.
Below are some attempts that I made.
1st Attempt
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
2nd Attempt
while (strcmp(pBook1->name, ""))
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
Also, consider the following code as the source code of my program:
#include <stdio.h>
#include <string.h>
#define MAX 50
struct Books
{
char name[MAX];
int ID;
float price;
};
void swap(struct Books *, struct Books *);
void main()
{
struct Books Book1, Book2, *pBook1, *pBook2;
pBook1 = &Book1;
pBook2 = &Book2;
// Input for the 1st book
printf("\n 1st Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook1->name, MAX, stdin);
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook1->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook1->price);
// Input for the 2nd book
printf("\n 2nd Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook2->name, MAX, stdin);
while (pBook2->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook2->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook2->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook2->price);
printf("\n Let's swap the info of the two books...");
swap(pBook1, pBook2);
printf("\n The info of the two books is now:");
printf("\n------------------------------ \n 1st Book \n ------------------------------------");
printf("\n Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook1->name, pBook1->ID, pBook1->price);
printf("\n------------------------------ \n 2nd Book \n ------------------------------------");
printf("Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook2->name, pBook2->ID, pBook2->price);
}
void swap(struct Books *pB1, struct Books *pB2)
{
char temp[MAX];
strcpy(temp, pB1->name);
strcpy(pB1->name, pB2->name);
strcpy(pB2->name, temp);
int tempID = pB1->ID, tempPrice = pB1->price;
pB1->ID = pB2->ID;
pB2->ID = tempID;
pB1->price = pB2->price;
pB2->price = tempPrice;
}
fgets reads until it encounters EOF, \n or N-1 bytes have been read. So if a user of your program presses enter, it will read \n and stop. Which means that pBook1->name[0] == '\n'. That is why your check for equality with "" fails and why pBook1->name[0] == '\0' fails.
See this example.
That means that you need to check for \n and \0 in case the user entered Ctrl-D which is how you enter EOF on *nix systems.
When you press enter pBook1->name[0] will become \n. You can use some functions as strlen to be sure there something in name.
I am trying to have the user enter for the first, middle, and last name in my struct. The first scan works fine, any after that do not work. Here's my code so far
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "contacts.h"
int main (void)
{
// Declare variables here:
struct Name names;
char yesNo;
// Display the title
printf("Contact Management System\n");
printf("-------------------------\n");
// Contact Name Input:
printf("Please enter the contact's first name: ");
scanf ("%d", &names.firstName);
printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf(" %c", &yesNo);
while (yesNo == 'y' || yesNo == 'Y') {
printf("Please enter the contact's middle initial(s): ");
scanf(" %c%d", &names.middleInitial);
yesNo = 'n';
}
printf("Please enter the contact's last name: ");
scanf(" %c%d", &names.lastName);
Here's the struct in my header file
struct Name {
char firstName[31];
char middleInitial[7];
char lastName[36];
};
When I enter more than one character the program ends, when I enter just one character, the program skips the second scanf. I had the program working beforehand but I realized I needed to use structs so I switched from int's to the struct, and I haven't been able to make it work this way.
You are using scanf wrong.
scanf ("%d", &names.firstName);
names.firstName is a char array, but you are using %d which expects a
pointer to int, you are passing a pointer to an array. This is correct:
scanf("%30s", names.firstName);
Then you do
scanf(" %c%d", &names.middleInitial);
which has two errors: you are giving two conversion but passing only a on
pointer, and you are again passing the wrong pointer. Correct:
scanf("%6s", names.middleInitial);
and the same applies for scanf(" %c%d", &names.lastName);, the correct version
scanf("%35s", names.lastName);
In general, when using scanf with %s, you will have the problem that newline
and other strings are kept in the input buffer. This happens because %s
matches a sequence of non-white-space characters, so the newline (entered when
ENTER is pressed) will remain in the input buffer. Another example is
if the user enters two word separated by at least an empty space (like Hello Word),
%s would only read Hello. Subsequent calls of scanf may fail if they don't
anticipate this. That's why the best strategy is to clean the
buffer, use this function:
void clean_file_buffer(FILE *fp)
{
int c;
while((c = fgetc(fp)) != '\n' && c!=EOF);
}
And the you can use it like this:
printf("Please enter the contact's first name: ");
scanf ("%30s", names.firstName);
clean_file_buffer(stdin);
that takes care of left overs.
If you however want to have more control over the whole line, then you should
use fgets instead to read the whole line and then you can use sscanf to
parse it.
scanf("%s", names.firstName);
scanf(" %c", &yesNo);
scanf(" %s", names.middleInitial);
scanf(" %s", names.lastName);
or
scanf("%s", names.firstName);
getchar();
scanf("%c", &yesNo);
getchar();
scanf("%s", names.middleInitial);
getchar();
scanf("%s", names.lastName);
getchar();
and when yesNo question, if you typed over 1 character, first character will be into yesNo variable, and other chars will be into next input variable(names.middleInitial).
If you want to check the yesNo more carefully,
input yesNo as string. (but, buffer size check needed. buffer overflow.)
char yesNos[100];
scanf(" %s", &yesNos) ;
if ( yesNos[0]=='y' ) {...}
I am having trouble getting this program to print the strings I enter properly. It keeps telling me that I have not entered data, even when I have. I also can't get the strings to compare to run my if statement. Thank for any help.
#include <stdio.h>
//function prototype
void enterPerson();
void enterChoice();
//global variables
char person[30];
char choice;
int main(void) {
enterPerson();
enterChoice();
printf("Please try the Precipitation Program again.\n");
return 0;
}
void enterPerson(){
// Ask for person name
printf("Please enter name:\n");
scanf("%s", &person);
//-------------------------------------------
printf("person is %s\n", person);
//-------------------------------------------
}
void enterChoice(){
//initialize choice
choice = "M";
//ask what they choose
printf("Do you choose test or rate? (Enter T for test R for rate)\n");
scanf("%c", &choice);
printf("Xchoice is: %c\n", choice);
if ((choice == 'T')||(choice == 'R')){
printf("choice is: %c\n", choice);
}
else{
printf("Incorrect or no data was input at this time\n");
}
}
As mentioned in comments, there are at least 3 problems:
scanf("%s", person); - do not take the address of char array.
scanf(" %c", &choice); - insert space to ignore whitespace.
choice = 'M'; - "M" is a string literal, while choice is char.
There is a linefeed (0xa) character left in the input buffer. You can see it by printing the choice variable after your scanf line with:
scanf("%c", &choice);
printf("c: %x\n", choice);
There are several options to get rid of this. Easiest is explained here.
Also there is a problem in:
scanf("%s", &person);
Character array name in C points to the first character, so you should fix this with:
scanf("%s", person);