C How to get number of players and their names - c

Hi am trying to learn how to program and i would like the user to input how many players there are as well as their first names. i thought i was correct with my following code after watching some youtube videos and looking elsewhere online but i cannot see where i have gone wrong. if someone could please help that would be awesome.
int main() {
int i, player_num;
char names[8][25];
printf("\n\n");
//user inputs value of player_num, here, as you have now
for(i = 0; i < player_num; i++) {
printf("Enter the player's name: ");
scanf("%s", names[i]); //enters name and creates a newline <enter key>
getchar(); //removes the newline from the keyboard buffer
}
printf("\n\n");
for(i = 0; i < player_num; i++)
printf("\n%s", names[i]);
printf("\n\n\t\t\t press enter when ready");
getchar(); //holds the console window open until you press enter
return 0;
}

You want to enter the number of player. It seems that you have already written code for entering players name. So for entering number of Player you need to use one scanf()
int main()
{
int i, player_num;
char names[8][25];
printf("\n\n");
//user inputs value of player_num, here, as you have now
printf("Enter the number of player(from 1 to 8)\n");
scanf_s("%d",&player_num,sizeof(int));
for(i = 0; i < player_num; i++) {
printf("Enter the player's name: ");
scanf_s("%s", names[i],25); //enters name and creates a newline <enter key>
getchar(); //removes the newline from the keyboard buffer
}
printf("\n\n");
for(i = 0; i < player_num; i++)
printf("\n%s", names[i]);
printf("\n\n\t\t\t press enter when ready");
getchar(); //holds the console window open until you press enter
return 0;
}
Hope this Helps :)

Related

String not scanned 2nd time when using gets function [duplicate]

This question already has answers here:
Using scanf and fgets in the same program?
(4 answers)
Closed 10 months ago.
When I am using gets function to scan item name in the first loop it runs properly but in the 2nd loop, it skips to Quantity quant without scanning item name.
I also tried using %s previously then it is working fine.
#include <stdio.h>
struct Dmart
{
char item[10];
int quant, price;
};
int main()
{
int i;
struct Dmart cust1[3], cust2[3];
printf("\nFor Customer 1\n");
for (i = 0; i < 3; i++)
{
printf("Item: ");
gets(cust1[i].item);
printf("Quantity: ");
scanf("%d", &cust1[i].quant);
printf("Price: ");
scanf("%d", &cust1[i].price);
printf("\n");
}
printf("\nFor Customer 2\n");
for (i = 0; i < 3; i++)
{
printf("Item: ");
gets(cust2[i].item);
printf("Quantity: ");
scanf("%d", &cust2[i].quant);
printf("Price: ");
scanf("%d", &cust2[i].price);
printf("\n");
}
printf("\nBill of Customer 1\n");
printf("Item\t\tQuantity\tPrice\n");
for (i = 0; i < 3; i++)
{
printf("%s\t\t%d\t\t%d\n", cust1[i].item, cust1[i].quant, cust1[i].price);
}
printf("\nBill of Customer 1\n");
printf("Item\t\tQuantity\tPrice\n");
for (i = 0; i < 3; i++)
{
printf("%s\t\t%d\t\t%d\n", cust2[i].item, cust2[i].quant, cust2[i].price);
}
return 0;
}
[VS Code Terminal Output][1]
The function gets is unsafe and is not supported by the C Standard. So do not use it.
The problem of the code is that after this call of scanf
scanf("%d", &cust2[i].price);
the new line character '\n' that corresponds to the pressed key Enter still is in the input buffer. So the next call of gets reads an empty string encountering at once the new line character.
Instead you could either always use the function fgets and then convert the entered string to an integer for integer data members of the structure or you can use scanf instead of gets like for example
for (i = 0; i < 3; i++)
{
printf("Item: ");
scanf( " %9[^\n]", cust1[i].item);
printf("Quantity: ");
scanf("%d", &cust1[i].quant);
printf("Price: ");
scanf("%d", &cust1[i].price);
printf("\n");
}
Pay attention to the leading space in the format string
scanf( " %9[^\n]", cust1[i].item);
^^^^
It allows to skip white spaces in the input buffer.

Split a phone number into three groups

I have a problem with a program that should split a phone number(ex. 1231231234) that user enters into three groups and display them like this (123)-123-1234. I'm not sure how to split this number and what to use in order to complete it. I didn't completed the code party but here's what i got.
#define SIZE 3
int main(void){
int option, j;
int phList = 0;
int phoneNum[SIZE];
printf("---=== Phone Numbers ===---\n");
while(1){
printf("\n");
printf("1. Display Phone List\n");
printf("2. Add a Number\n");
printf("0. Exit\n");
printf("\n");
printf("Please select from the above options: ");
scanf("%d", &option);
if(option == 0){
printf("Exiting Phone Number App. Good Bye!!!\n");
return 0;
}
if(option == 1){
printf("\n");
printf("Phone Numbers\n");
printf("==============\n");
for(j = 0; j < phList; j++){
printf("\n", phoneNum[j]);
}
}
if(option == 2){
if(phList < SIZE){
printf("\n");
printf("Add a Number\n");
printf("============\n");
scanf("%d", &phoneNum[phList]);
phList++;
} else {
printf("Add a Number\n");
printf("============\n");
printf("ERROR!!! Phone Number List is F$
}
}
}
return 0;
}
I would consider using fgets() to get the phone number as a string, rather than getting it as an integer. Then you can filter the input so that only the digits are kept, allowing users to enter parenthesis, spaces, or dashes as desired. Finally, sscanf() can be used to scan the filtered string into three strings for the area code, exchange number, and subscriber number. If you like, these strings can be converted to numbers by atoi() or strtol().
The OP seems to be assuming that the phone number follows the format of the North American Numbering Plan, but phone number formats may differ. The string representation is more flexible than an integer representation, making future modifications to the code easier.
Here is an example of how this might be done:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void filter_num(char *str);
int main(void)
{
char buffer[1000];
char area_code[4];
char xch_num[4];
char sub_num[5];
printf("Enter phone number: ");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
fprintf(stderr, "Error in fgets\n");
exit(EXIT_FAILURE);
}
filter_num(buffer);
if (sscanf(buffer, "%3s%3s%4s", area_code, xch_num, sub_num) != 3) {
fprintf(stderr, "Phone number format error\n");
exit(EXIT_FAILURE);
}
printf("Phone number is: (%s) %s-%s\n",
area_code, xch_num, sub_num);
return 0;
}
void filter_num(char *str)
{
char *p = str;
while (*p != '\0') {
if (isdigit(*p)) {
*str++ = *p;
}
++p;
}
*str = '\0';
}
I will suggest defining a function to split the number and display that, Please have a look on this one, I have written it for you just now and works fine:
void DisplayNum(long long int PhNum)
{
printf("\n ");
for(int i=1; i<=10; ++i) // Since Phone Number Contains 10 digits
{
int digit= PhNum/(pow(10,10-i)); // Spliting digits
digit= digit%10;
if(i==1)
{
printf(" (");
}
if(i==4)
{
printf(")-");
}
if(i==7)
{
printf("-");
}
printf("%d",digit); // Displaying Digits
}
}
But make sure to use #include<math.h> at the beginning because i am using pow() function here. Then you can just pass each Phone Number in array to display to this function. The for-loop to display each Phone Number in array will be like :
for(j = 0; j < phList; j++){
DisplayNum(phoneNum[j]);
}

fgets not waiting for user input

In the given code fgets is not waiting for input.
I tried using scanf but it's giving unusual error(Exception thrown at 0x0F74DDF4 (ucrtbased.dll)). I'm using Visual Studio 2015 for debugging my code. Can anyone explain why fgets is not waiting for input?
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
//GLOBAL-VARIABLE DECLARTION
#define MAX 1000
//GLOBAL-STRUCTURES DECLARATION
struct census
{
char city[MAX];
long int p;
float l;
};
//GLOBAL-STRUCTURE-VARIABLE DECLARATION
struct census cen[] = { 0,0,0 };
//USER-DEFINED FUNCTION
void header();
void header()
{
printf("*-*-*-*-*CENSUS_INFO*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
main()
{
//VARIABLE-DECLARATION
int i = 0, j = 0;
//int no_of_records = 0;
//FUNCTION CALL-OUT
header();
printf("Enter No. of City : ");
scanf_s("%d", &j);
printf("\n\n");
printf("Enter Name of City, Population and Literacy level");
printf("\n\n");
for (i = 0;i < j;i++)
{
printf("City No. %d - Info :", i + 1);
printf("\n\n");
printf("City Name :");
fgets(cen[i].city, MAX, stdin);
printf("\n");
printf("Population : ");
scanf_s("%d", &cen[i].p);
printf("\n");
printf("Literacy : ");
scanf_s("%f", &cen[i].l);
printf("\n");
}
//TERMINAL-PAUSE
system("pause");
}
When you enter the number of cities and press Enter, scanf doesn't read the linebreak character from input. fgets then tries to read but finds the linebreak, and immediately stops.
Don't use scanf to read numbers, use fgets to read in string first and then sscanf(or strtol/strtof/strtod) to convert to number.
char temp[LIMIT];
if(fgets(temp, LIMIT, stdin)) {
if(sscanf(temp, "%d", &j) == 1) {
// Ok
}
else {
// Handle sscanf error
}
}
else {
// Handle fgets error
}
I always use fgets followed by sscanf.
Declare this at the top,
char line[MAX];
Then use fgets to get a line, and sscanf to parse the int value out of it,
printf("Enter No. of City : ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &j);
Similar pattern for l
printf("Literacy : ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%f", &cen[i].l);

Taking some string input from user with C

I am not too familiar with C syntax. I need to process some data based on user input. Although I processed the data successfully but I am stuck at user input section. I removed the unnecessary data processing section and made a simple example of how I am taking the user input. Can anyone tell me what's the problem with below code :
int i, number;
char *str;
str=(char*)malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
scanf ("%[^\n]%*c", str);
printf("%s", str);
}
Output:
"Enter count : " appears fine, but whenever I provide some value and hit enter it's showing me only 'count' number of Enter string: without enabling user to enter the string.
For example -
Enter count : 2
Enter string:
Enter string:
But if I discard the count input section and provide any fixed value, like
for(i=0; i<5; i++)
it works fine
Thanks in advance
FYI, there is no issue in for(i=0; i<number; i++), problem is in scanning logic.
Actually, scanf ("%[^\n]%*c", str); is not right. you should use %s to read strings, not %c, which reads a single character, including the ENTER (newline).
Rather, i would suggest, use fgets() for inputs. It's a whole lot better in every way. Check the man page here.
Maybe you can use something like
//Dummy code
int i, number;
char *str;
printf("Enter count : ");
scanf("%d", &number);
str=malloc(number*sizeof(char)); //yes, casting not required
fgets(str, (number-1), stdin ); //"number" is used in different context
fputs(str, stdout);
EDIT:
Working code
#include <stdio.h>
#include <stdlib.h>
#define SIZ 1024
int main()
{
int i, number;
char * str = malloc(SIZ * sizeof (char));
printf("Enter the number :\n");
scanf("%d", &number);
getc(stdin); //to eat up the `\n` stored in stdin buffer
for (i = 0; i < number; i++)
{
printf("Enter the string %d :", (i+1));
fgets(str, SIZ-1, stdin);
printf("You have entered :");
fputs(str, stdout);
}
return 0;
}
scanf("%s",str); Use this instead of the code you are using to take string inputs in a character array.
There is a newline character \n after entering count value which is picked up by %c in your scanf()
Just use %s to scan strings as shown below.
scanf("%s",str);
If there are spaces in your input.
Then do
char c[50];
fgets(c,sizeof(c),stdin);
Check the below code:
#include <stdio.h>
#include<stdlib.h>
int main(){
int i, number;
char *str;
str=malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d%*c", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
fgets(str,1000,stdin);
printf("%s", str);
}
}

Input check after scanf goes wrong

Here's a part of a function that supposed to scan an integer between 0 and 100.
The program goes wrong when the user inputs a char. anyone has an idea? iv'e tried a Combined condition like this one: if(scanf("%d",&test)&&(test<=100&&test>=0))
it didn't work...
while(i!=4)
{
printf("\nPlease enter your homework grade: ");
if(scanf("%d",&hw))
{
++i;
}
if(hw<=100&&hw>=0)
{
++i;
}
printf("\nPlease enter your test grade: ");
if(scanf("%d",&test))
{
++i;
}
if(test<=100&&test>=0)
{
++i;
}
else
{
printf("\nPlease re-enter the required details\n");
i=0;
}
}
When a character is read using %d then the ASCII value of it is stored in the memory.
If you want a Integer Proofing mechanism, then use the below code. Get the user input as a string, check if any character is present, if present then return error, else convert that string to integer and use the same for further processing.
char n[4]; /* To store max of 3 char's `100` including '\0' */
int i=0, flag=1;
scanf("%3s", n);
while(n[i] != '\0'){
flag = isdigit(n[i]);
if (!flag)
break;
i++;
}
if(flag)
{
i=atoi(n);
printf("%d", i);
}
else
{
printf("it's not integer");
}
you have to make while(i!=2){....}
Try the program in this way....
main()
{
int i, hw, test;
while(i!=2)
{
i=0;
printf("\nEnter the hmwrk grade: ");
if(scanf("%d",&hw)&&(hw<=100&&hw>=0))
++i;
printf("\nEnter the test grade: ");
if(scanf("%d",&test)&&(test<=100&&test>=0))
++i;
if(i!=2)
printf("\nPlease reenter the req details..\n");
}
}

Resources