Program fails to receive second input - c

It's just a code to receive user inputs in C program, but fails to do so and accepts null space as input. I have tried fgets() as well and the same thing keeps happening. Please advice on how to fix.
#include <math.h>
#include <stdio.h>
//#include <string.h>
#define len 16
int main(void)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,i=0,j=0;
printf("enter the number of cards:");
n = getchar();
//scanf("%d",&n);
int c1[len][n],card[len][n];
char buf[len];
printf("Enter card number:");
gets(buf);
system("Pause");
return (0);
}

"...code to receive user inputs in c program, but fails to do so and accepts null space as input..."
The reasons your existing code has problems is covered well in the comments under your post.
Consider a different approach: Define the following:
char inBuf[80] = {0};//
int numCards = 0;//Pick variable names that are descriptive (n is not)
int cardNum = 0;
bool isnum;
Then use it in conjunction with printf() etc.
printf("enter the number of cards:");
if(fgets(inBuf, sizeof(inBuf), stdin))//will read more than just a single char, eg. "12345"
{
int len = strlen(inBuf);
isnum = true;
for(int i=0;i<len;i++)
{
if(!isdigit(inBuf[i]))
{
isnum = false;
break;
}
}
if(isnum)
{
numCards = atoi(inBuf);
}
else
{
printf("input is not a number\n"
}
}
printf("Enter card number:");
if(fgets(inBuf, sizeof(inBuf), stdin))
{
...
Repeat variations of these lines as needed to read input from stdin, with modifications to accommodate assignment statements based on user input i.e. an integer (this example is covered), a floating point number, a string (eg. a persons name)
Although there is more that you can do to improve this, it is conceptually viable for your stated purpose...

Related

Counting Number Of User Input in C Program

printf("Enter number of patients:");
int numberOfInputs = scanf("%d", &patients);
if (numberOfInputs != 1) {
printf("ERROR: Wrong number of arguments. Please enter one argument d.\n");
}
I am asking the user to input one number as an argument, but would like to print out a statement if the user does not input anything or puts in more than one input. For example, once prompted with "Enter number of patients:", if the user hits enter without entering anything, I would like to print out a statement. The code above is what I have been specifically tinkering around with it for the past couple hours as a few previous posts on this site have suggested but when I run it in terminal, it does not work. Any suggestions? Thank you in advance, and all advice is greatly appreciated!
If I understand your question right, you want to print an error when the input is anything other than an integer and this includes newline as well. You can do that using a char array and the %[] specifier.
Example:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int patients;
char str[10];
printf("Enter number of patients:");
int numberOfInputs = scanf("%[0-9]", str);
if (numberOfInputs != 1) {
printf("ERROR: Wrong number of arguments. Please enter one argument.\n");
}
patients = atoi(str); //This is needed to convert the `str` back to an integer
}
This will print the error when the user just hits ENTER as well.
This looks super over-complicated, but it basically splits the input, checks it to be exactly one and than checks it to be an integer (and converts it). It works fine in loop as well and handles empty input.
I'm sure there are more elegant solutions to this problem, it's just a suggestion.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
int getNumberOfInput(char* str);
bool isNumber(char* str);
int main()
{
char str[512];
while(1)
{
printf("Enter text: ");
fgets(str, 512, stdin);
int numberOfInput = getNumberOfInput(str);
if ( numberOfInput == 0 )
printf("You must give an input\n");
else if ( numberOfInput > 1 )
printf("You have to give exactly one input\n");
else
{
if (!isNumber(str))
printf("The input is not an integer\n");
else
{
int input = atoi(str);
printf("input: %d\n", input);
}
}
}
return 0;
}
int getNumberOfInput(char* str)
{
char* word = strtok(str, " \t\n\v\f\r");
int counter = 0;
while(word != NULL)
{
++counter;
word = strtok(NULL, " \t\n\v\f\r");
}
return counter;
}
bool isNumber(char* str)
{
int i, len = strlen(str);
for (i=0; i<len; ++i)
if (!isdigit(str[i]))
return false;
return true;
}

How to scan initial spaces in C

I have a typical question it's not that how can I scan spaces using scanf but how to scan the initial spaces entered in a string
This is what I've done:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char a[10];
scanf("%d",&n);
scanf(" %[^\n]",a);
printf("%d",strlen(a));
return 0;
}
and when I run the program with following input:
aa bb//note there are two spaces before initial a
and the output is 6 but there are 8 characters i.e, 2 spaces followed by 2 a's followed by 2 spaces and then lastly 2 b's
I eve tried an own function.. but alas! the length is 6. Here's my function:
int len(char a[101])
{
int i;
for(i=0;a[i];i++);
return i;
}
What I think is that the initial 2 spaces are being ignored...or I might be wrong. It'd be great if someone could explain why the length of string is 6 and how can I make it 8 or accept all the 8 characters I mentioned above.
EDIT: this is my actual code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,N,j,k;
char **ans,s[101];
scanf("%d",&N);
ans=(char **)calloc(N,sizeof(char*));
for(j=0,i=0;i<N;i++)
{
scanf(" %[^\n]",s);
printf("%d",strlen(s));
ans[i]=(char*)calloc(strlen(s),sizeof(char));
for(k=0,j=((strlen(s)/2)-1);j>=0;j--,k++)
{
ans[i][k]=s[j];
}
for(j=strlen(s)-1;j>=strlen(s)/2;k++,j--)
{
ans[i][k]=s[j];
}
}
for(i=0;i<N;i++)
{
printf("%s\n",ans[i]);
}
scanf("%d",&i);
return 0;
}
OP code should work as posted.
OP comments true code is using scanf(" %[^\n]",a); which fully explains the problem: the space in the format is consuming leading white-space.
To address other issues with scanf(), see following.
fgets() is the right tool.
Yet if OP insists on scanf()
how can I scan spaces using scanf but how to scan the initial spaces entered in a string?
char buf[100];
// Scan up to 99 non\n characters and form a string in `buf`
switch (scanf("%99[^\n]", buf)) {
case 0: buf[0] = '\0'; break; // line begins with `'\n`
// May want to check if strlen(buf)==99 to detect a long line
case 1: break; // Success.
case EOF: buf[0] = '\0'; break; // stdin is closed.
}
fgetc(stdin); // throw away the \n still in stdin.
The issue i believe is that you need to be getting length from a Pointer to the array not the array itself.
Try this, this code worked for me.
int ArrayLength(char* stringArray)
{
return strlen(stringArray);
}

Find Biggest Number in C, by N number of inputs

So I have this code:
#include <stdio.h>
int main()
{
char peopleName[5][20],peopleAge[5];
int i;
int maxAge=0, maxName=-1;
for(i=0;i<5;i++)
{
printf("Name & Age %d :",i+1);
scanf("%s",&peopleName[i]);
scanf("%d",&peopleAge[i]);
if(peopleAge[i]>maxAge)
{
maxAge=peopleAge[i];
maxName=i;
}
}
printf("%s %d", peopleName[maxName],peopleAge[maxAge]);
}
This code finds from 5 people the oldest one. I want to change from 5 people to N number of people, whatever the number I input myself. (For example I put 7, and I can insert seven names and ages and so on).
The question has two parts: How does the user specify how many persons are entered? And how do I store the data?
The second part is easy: No matter how many persons you are going to consider, if you just want to know who is the oldest, it is enough to keep the name and age of the currently oldest person. (Of course, if there is a tie and many people are, say, 80 years old, you just get to keep the first match.)
Not storing anything also simplifies the first question. You could ask the user to specify the number of persons beforehand and that's find if you have few people. If you have a list of many people, the user would have to count the by hand and then enter the count. Miscounting is very likely.
A better way is to indicate the end of input by another means, for example by a negative age or by two dashes as name. There is also the possibility that the input runs out, for example when redirecting input from a file or when pressing one of Ctrl-Z or Ctrl-D, depending on your platform, after the input.
The example below read the input line-wise and then scans that line. The loop while (1) is in theory infinite, in practice execution breaks out of the loop when the input runs out – fgets return NULL –, when a blank line is read or when the input isn't in the format single-word name and age.
#include <stdio.h>
int main(void)
{
char oldest[80] = "no-one";
int max_age = -1;
int count = 0;
puts("Enter name & age on each line, blank line to stop:");
while (1) {
char line[80];
char name[80];
int age;
if (fgets(line, sizeof(line), stdin) == NULL) break;
if (sscanf(line, "%s %d", name, &age) < 2) break;
if (age > max_age) {
strcpy(oldest, name);
max_age = age;
}
count++;
}
printf("The oldest of these %d people is %s, aged %d.\n",
count, oldest, max_age);
return 0;
}
You can do this -
int n; // number of people
scanf("%d",&n); // take input from user
char peopleName[n][20],peopleAge[n]; // declare 2-d array
for(i=0;i<n;i++)
{
// your code
}
Also this statement -
scanf("%s",&peopleName[i]); // pass char * as argument to %s
should be -
scanf("%19s",peopleName[i]); // one space is left for null character
You can use malloc to allocate buffer dynamically.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char (*peopleName)[20];
int *peopleAge;
int i;
int maxAge=0, maxName=-1;
int dataNum;
printf("How many people? :");
if(scanf("%d",&dataNum)!=1)return 1;
peopleName=malloc(sizeof(char[20])*dataNum);
peopleAge=malloc(sizeof(int)*dataNum);
for(i=0;i<dataNum;i++)
{
printf("Name & Age %d :",i+1);
scanf("%s",peopleName[i]);
scanf("%d",&peopleAge[i]);
if(peopleAge[i]>maxAge)
{
maxAge=peopleAge[i];
maxName=i;
}
}
printf("%s %d", peopleName[maxName],peopleAge[maxName]);
free(peopleName);
free(peopleAge);
return 0;
}
Also please note that:
You should pass char*, not char(*)[20], for %s in scanf
peopleAge[maxAge] may be out of bounds. maxName (or other name but same role) should suit here.

How to check if the user input an integer using scanf

I created a program to make a diamond out of *'s. I am looking for a way to check if the type of input is an integer in the C language. If the input is not an integer I would like it to print a message.
This is what I have thus far:
if(scanf("%i", &n) != 1)
printf("must enter integer");
However it does not display the message if it's not an integer. Any help/guidance with this issue would be greatly appreciated!
you can scan your input in a string then check its characters one by one, this example displays result :
0 if it's not digit
1 if it is digit
you can play with it to make your desired output
char n[10];
int i=0;
scanf("%s", n);
while(n[i] != '\0')
{
printf("%d", isdigit(n[i]));
i++;
}
Example:
#include <stdio.h>
#include <string.h>
main()
{
char n[10];
int i=0, flag=1;
scanf("%s", 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");
}
}
Use fgets() followed by strtol() or sscanf(..."%d"...).
Robust code needs to handle IO and parsing issues. IMO, these are best done separately.
char buf[50];
fgets(buf, sizeof buf, stdin);
int n;
int end = 0; // use to note end of scanning and catch trailing junk
if (sscanf(buf, "%d %n", &n, &end) != 1 || buf[end] != '\0') {
printf("must enter integer");
}
else {
good_input(n);
}
Note:
strtol() is a better approach, but a few more steps are needed. Example
Additional error checks include testing the result of fgets() and insuring the range of n is reasonable for the code.
Note:
Avoid mixing fgets() and scanf() in the same code.
{ I said scanf() here and not sscanf(). }
Recommend not to use scanf() at all.
strtol
The returned endPtr will point past the last character used in the conversion.
Though this does require using something like fgets to retrieve the input string.
Personal preference is that scanf is for machine generated input not human generated.
Try adding
fflush(stdout);
after the printf. Alternatively, have the printf output a string ending in \n.
Assuming this has been done, the code you've posted actually would display the message if and only if an integer was not entered. You don't need to replace this line with fgets or anything.
If it really seems to be not working as you expect, the problem must be elsewhere. For example, perhaps there are characters left in the buffer from input prior to this line. Please post a complete program that shows the problem, along with the input you gave.
Try:
#include <stdio.h>
#define MAX_LEN 64
int main(void)
{ bool act = true;
char input_string[MAX_LEN]; /* character array to store the string */
int i;
printf("Enter a string:\n");
fgets(input_string,sizeof(input_string),stdin); /* read the string */
/* print the string by printing each element of the array */
for(i=0; input_string[i] != 10; i++) // \0 = 10 = new line feed
{ //the number in each digits can be only 0-9.[ASCII 48-57]
if (input_string[i] >= 48 and input_string[i] <= 57)
continue;
else //must include newline feed
{ act = false; //0
break;
}
}
if (act == false)
printf("\nTHIS IS NOT INTEGER!");
else
printf("\nTHIS IS INTEGER");
return 0;
}
[===>] First we received input using fgets.Then it's will start pulling each digits out from input(starting from digits 0) to check whether it's number 0-9 or not[ASCII 48-57],if it successful looping and non is characters -- boolean variable 'act' still remain true.Thus returning it's integer.

How to prevent users from inputting letters or numbers?

I have a simple problem;
Here is the code :
#include<stdio.h>
main(){
int input;
printf("Choose a numeric value");
scanf("%d",&input);
}
I want the user to only enter numbers ...
So it has to be something like this :
#include<stdio.h>
main(){
int input;
printf("Choose a numeric value");
do{
scanf("%d",&input);
}while(input!= 'something');
}
My problem is that I dont know what to replace in 'something' ... How can I prevent users from inputting alphabetic characters ?
EDIT
I just got something interesting :
#include<stdio.h>
main(){
int input;
printf("Choose a numeric value");
do{
scanf("%d",&input);
}while(input!= 'int');
}
Adding 'int' will keep looping as long as I enter numbers, I tried 'char' but that didnt work .. surely there is something for alphabets right ? :S
Please reply !
Thanks for your help !
The strtol library function will convert a string representation of a number to its equivalent integer value, and will also set a pointer to the first character that does not match a valid number.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
...
int value;
char buffer[SOME_SIZE];
char *chk;
do
{
printf("Enter a number: ");
fflush(stdout);
if (fgets(buffer, sizeof buffer, stdin) != NULL)
{
value = (int) strtol(buffer, &chk, 10); /* assume decimal format */
}
} while (!isspace(*chk) && *chk != 0);
If chk points to something other than whitespace or a string terminator (0), then the string was not a valid integer constant. For floating-point input, use strtod.
You can't prevent the user from entering anything he wants -- you can only ignore anything s/he enters that you don't "like".
A typical pattern is to read a string with fgets, then scan through the string and check that all the input was digits with isdigit. If it was all digits, then convert to an integer; otherwise, throw it away and get the input again.
Alternatively, use strtol to do the conversion. It sets a pointer to the end of the data it could convert to a number; in this case you (apparently) want it to point to the end of the string.
If you don't mind some non-portable code, you can read one character at a time, and throw away anything but digits (e.g. with getch on Windows).
You should not use scanf to read in numbers - see http://www.gidnetwork.com/b-63.html
Use fgets instead.
However, if you must use scanf, you can do this:
#include <stdio.h>
int main() {
char text[20];
fputs("enter some number: ", stdout);
fflush(stdout);
if ( fgets(text, sizeof text, stdin) ) {
int number;
if ( sscanf(text, "%d", &number) == 1 ) {
printf("number = %d\n", number);
}
}
return 0;
}
Personally, I would read the input into a buffer and scan that string for my number.
char buffer[100];
float value;
do {
scanf("%s", buffer);
} while ( sscanf(buffer,"%f", &value) != 1 )
This will loop until the first thing the user enters on the line is a number. The input could be anything but will only get past this block when the first thing entered is a number.
example input:
43289 (value is 43289)
43.33 (value is 43.44)
392gifah (value is 392)
ajfgds432 (continues to loop)

Resources