I am trying to make a program that user can enter either an integer or character. And then the binary representation of the input will be printed. (ASCII code for chars). But only one of them works when I try to fix it.
You cannot use scanf if you don't know whether it should parse the input as an integer or a character.
Therefore, I suggest you first read the whole line with fgets instead and then determine afterwards whether it is an integer or a character that was entered, for example by using the function isdigit. Afterwards you can act accordingly, for example by calling sscanf, atoi, strtol or whatever function you want on the input.
Does this answer to your question?
#include<stdio.h>
void decToBinary(int n)
{
int binaryNum[32]; // array to store binary number
// counter for binary array
int i = 0;
while (n > 0)
{
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
printf("%d",binaryNum[j]);
}
int main()
{
char a;
char ch;
int b,num;
printf("What do you want to enter: character(C/c) or number(N/n) :");
scanf("%c",&a);
if((a=='C')||(a=='c'))
{
printf("\nEnter the character:");
scanf(" %c",&ch);
b=ch;
printf("\nASCII VALUE : %d",b);
}
else if((a=='N')||(a=='n'))
{
printf("\nEnter the number:");
scanf("%d",&num);
decToBinary(num);
}
else
printf("Invalid entry!!");
return 0;
}
User gives input and accordingly the pattern must be printed. It should encounter negative numbers and char as input. I encounterd the negative value as input but as I try to give char input it goes on ifinite loop. So how can I encounter char value for int data type as an input.
#include<stdio.h>
#include<conio.h>
/*
C program to print the pattern allowing user
to input the no. of lines.
*/
//Declaring method for printing pattern
void printPattern(int numberOfLines);
void main()
{
char userChoice;//User's choice to continue or exit
int numberOfLines;//User's input for number line to be printed
clrscr();
//Logic for printing the pattern
do
{
printf("Enter the number of lines you want to print \n");
scanf("%d",&numberOfLines);
//Countering issue if user enters a char insted of number
/*while()
{
printf("Enter number only \n");
scanf(" %c",&numberOfLines);
}*/
//Countering issue if user enters negative number
while(numberOfLines<=0)
{
printf("Enter positive number \n");
scanf("%d",&numberOfLines);
}
//Calling method to the start printing of method
printPattern(numberOfLines);
//Taking user's choice to continue or not
printf("Press Y to continue else any other key to exit \n");
scanf(" %c",&userChoice);
}
while(userChoice == 'y' || userChoice == 'Y');
}
/*
Method definition for printing the pattern
Argument numberOfLines: User's input for number of lines
*/
void printPattern(int numberOfLines)
{
int i,j;
for(i=0 ; i<numberOfLines ; i++) //for rows
{
for(j=0 ; j<=i ; j++) //for columns
{
printf("$");
}
printf("\n"); //for going to next row after printing one
}
}```
When you do scanf("%d",&numberOfLines); you want to read an integer. If you then enter a letter, like an a, nothing will be read from the input stream. In other words, you'll go into an endless loop where you keep trying to read an integer but the stream contains a letter.
You need to remove that letter from the stream.
You could try:
while(scanf("%d",&numberOfLines) != 1)
{
// Didn't get an integer so remove a char
getchar();
}
However, that will lead to problems if the input stream fails.
The better solution is to use fgets and sscanf
Here is a shorter, simpler version of printPattern
void printPattern(int n)
{
char dollar[n];
memset(dollar, '$', n);
for(int i = 1; i <= n; ++i)
printf("%.*s\n", i, dollar);
}
What is wrong with this ? Also, I have to use scanf(). It is supposed to read any integers and sum them, the loop is to stop when 0 is entered..
main (void){
int a;
int r=0;
while(scanf(" %d",&a)){
r=r+a;
}
printf("the sum is %d\n",r);
return 0;
}
Quoting from man
These functions return the number of input items assigned. This
can be
fewer than provided for, or even zero, in the event of a matching fail-
ure. Zero indicates that, although there was input available, no conver-
sions were assigned; typically this is due to an invalid input character,
such as an alphabetic character for a `%d' conversion.
The value EOF is
returned if an input failure occurs before any conversion such as an end-
of-file occurs. If an error or end-of-file occurs after conversion has
begun, the number of conversions which were successfully completed is
returned.
So, that pretty much explains what is returned by scanf().
You can solve the problem by adding ( 1 == scanf("%d", &a) && a != 0 ) as the condition in your while loop like
int main (void)
{
int a;
int r=0;
while( 1 == scanf("%d", &a) && a != 0 )
{
r=r+a;
}
printf("the sum is %d\n",r);
return 0;
}
Also note that you have to specify the type of main as int main().
I would also like to add that the loop will end when you enter a character like 'c' ( or a string ) and it will show the sum of all the numbers you entered before entering the character.
scanf() doesn't return what it has written to the variable. It returns the total number of items successfully filled.
EDIT:
You would be much better off using fgets() to read from stdin and then using sscanf() to get the integer, which you can check against 0.
#define BUFF_SIZE 1024
int main (void)
{
int a;
int r = 0;
char buffer[BUFF_SIZE] = {0};
while(1) {
fgets(buffer, sizeof buffer, stdin);
sscanf(buffer, "%d", &a);
if(!a)
break;
r = r + a;
}
printf("the sum is %d\n", r);
return 0;
}
For example, if I want to write a code to average an unspecified number of numbers that the user enters, how can I make it so that the user can determine the number of numbers? ie. if the user wants to average just three numbers, he types them in one at a time, and then types in something to signal that this is it.
I wrote something like
while(i!=EOF){
printf("type in a number: \n");
scanf("%f",&i);
array[x]=i;
x++;
}
"and then some code to average the numbers in the array".
The idea was that if the user wants to signal that he finished entering numbers, he types in EOF and then the while loop will stop, however this isn't working. When I type in EOF at the terminal, it just writes "type in a number:" indefinitely.
scanf returns information in two different ways: in the variable i, and as its return value. The content of the variable i is the number that scanf reads, if it is able to return a number. The return value from scanf indicates whether it was able to read a number.
Your test i != EOF is fundamentally a type error: you're comparing the error indicator value EOF to a variable designed to hold a floating-point number. The compiler doesn't complain because that is accidentally valid C code: EOF is encoded as an integer value, and that value is converted to a floating-point value to perform the comparison. In fact, you'll notice that if you enter -1 at the prompt, the loop will terminate. -1 is the value of the EOF constant (on most implementations).
You should store the return value of scanf, and store it into a separate variable. If the return value is EOF, terminate the loop. If the return value is 1, you have successfully read a floating-point value.
If the return value is 0, the user typed something that couldn't be parsed. You need to handle this case appropriately: if you do nothing, the user's input is not discarded and your program will loop forever. Two choices that make sense are to discard one character, or the whole line (I'll do the latter).
double i;
double array[42];
int x = 0;
int r = 0;
while (r != EOF) {
printf("type in a number: \n");
r = scanf("%f", &i);
if (r == 1) {
/* Read a number successfully */
array[x] = i;
x++;
} else if (r == 0) {
printf("Invalid number, try again.\n");
scanf("%*[^\n]"); /* Discard all characters until the next newline */
}
}
You should also check that x doesn't overflow the bounds of the array. I am leaving this as an exercise.
I want to do it by typing in something that's not a number
Then get the input as a string, and exit if it cannot be converted to a number.
char buf[0x80];
do {
fgets(buf, sizeof(buf), stdin);
if (isdigit(buf[0])) {
array[x++] = strtod(buf);
}
} while(isdigit(buf[0]);
In case of no input scanf() does not set i to EOF but rather can return EOF. So you should analyze scanf() return code. By the way you can receive 0 as result which actually means there is no EOF but number cannot be read.
Here is example for you:
#include <stdio.h>
#define MAX_SIZE 5
int main()
{
int array[MAX_SIZE];
int x = 0;
int r = 0;
while (x < MAX_SIZE)
{
int i = 0;
printf("type in a number: \n");
r = scanf("%d",&i);
if (r == 0)
{
printf("ERROR!\n");
break;
}
if (r == EOF)
{
printf("EOF!\n");
break;
}
array[x]=i;
x++;
}
}
You cannot write 'EOF'.. since you are reading into a number...
EOF equals -1.. so if he enterd that, the loop would stop
You can test for the return value of the scanf function. It returns EOF on matching failure or encountering an EOF character.
printf("type in a number:" \n);
while(scanf("%f",&i)!=EOF){
array[x]=i;
x++;
printf("type in a number:" \n);
}
The catch is that I cannot use atoi or any other function like that (I'm pretty sure we're supposed to rely on mathematical operations).
int num;
scanf("%d",&num);
if(/* num is not integer */) {
printf("enter integer");
return;
}
I've tried:
(num*2)/2 == num
num%1==0
if(scanf("%d",&num)!=1)
but none of these worked.
Any ideas?
num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).
As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
You need to read your input as a string first, then parse the string to see if it contains valid numeric characters. If it does then you can convert it to an integer.
char s[MAX_LINE];
valid = FALSE;
fgets(s, sizeof(s), stdin);
len = strlen(s);
while (len > 0 && isspace(s[len - 1]))
len--; // strip trailing newline or other white space
if (len > 0)
{
valid = TRUE;
for (i = 0; i < len; ++i)
{
if (!isdigit(s[i]))
{
valid = FALSE;
break;
}
}
}
There are several problems with using scanf with the %d conversion specifier to do this:
If the input string starts with a valid integer (such as "12abc"), then the "12" will be read from the input stream and converted and assigned to num, and scanf will return 1, so you'll indicate success when you (probably) shouldn't;
If the input string doesn't start with a digit, then scanf will not read any characters from the input stream, num will not be changed, and the return value will be 0;
You don't specify if you need to handle non-decimal formats, but this won't work if you have to handle integer values in octal or hexadecimal formats (0x1a). The %i conversion specifier handles decimal, octal, and hexadecimal formats, but you still have the first two problems.
First of all, you'll need to read the input as a string (preferably using fgets). If you aren't allowed to use atoi, you probably aren't allowed to use strtol either. So you'll need to examine each character in the string. The safe way to check for digit values is to use the isdigit library function (there are also the isodigit and isxdigit functions for checking octal and hexadecimal digits, respectively), such as
while (*input && isdigit(*input))
input++;
(if you're not even allowed to use isdigit, isodigit, or isxdigit, then slap your teacher/professor for making the assignment harder than it really needs to be).
If you need to be able to handle octal or hex formats, then it gets a little more complicated. The C convention is for octal formats to have a leading 0 digit and for hex formats to have a leading 0x. So, if the first non-whitespace character is a 0, you have to check the next character before you can know which non-decimal format to use.
The basic outline is
If the first non-whitespace character is not a '-', '+', '0', or non-zero decimal digit, then this is not a valid integer string;
If the first non-whitespace character is '-', then this is a negative value, otherwise we assume a positive value;
If the first character is '+', then this is a positive value;
If the first non-whitespace and non-sign character is a non-zero decimal digit, then the input is in decimal format, and you will use isdigit to check the remaining characters;
If the first non-whitespace and non-sign character is a '0', then the input is in either octal or hexadecimal format;
If the first non-whitespace and non-sign character was a '0' and the next character is a digit from '0' to '7', then the input is in octal format, and you will use isodigit to check the remaining characters;
If the first non-whitespace and non-sign character was a 0 and the second character is x or X, then the input is in hexadecimal format and you will use isxdigit to check the remaining characters;
If any of the remaining characters do not satisfy the check function specified above, then this is not a valid integer string.
First ask yourself how you would ever expect this code to NOT return an integer:
int num;
scanf("%d",&num);
You specified the variable as type integer, then you scanf, but only for an integer (%d).
What else could it possibly contain at this point?
If anyone else comes up with this question, i've written a program, that keeps asking to input a number, if user's input is not integer, and finishes when an integer number is accepted
#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>
bool digit_check(char key[])
{
for(int i = 0; i < strlen(key); i++)
{
if(isdigit(key[i])==0)
{
return false;
}
}
return true;
}
void main()
{
char stroka[10];
do{
printf("Input a number: ");
scanf("%s",stroka);}
while (!digit_check(stroka));
printf("Number is accepted, input finished!\n");
system("pause");
}
I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!
#include<stdio.h>
int iFunctErrorCheck(int iLowerBound, int iUpperBound){
int iUserInput=0;
while (iUserInput==0){
scanf("%i", &iUserInput);
if (iUserInput==0){
printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
getchar();
}
if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
iUserInput=0;
}
}
return iUserInput;
}
Try this...
#include <stdio.h>
int main (void)
{
float a;
int q;
printf("\nInsert number\t");
scanf("%f",&a);
q=(int)a;
++q;
if((q - a) != 1)
printf("\nThe number is not an integer\n\n");
else
printf("\nThe number is an integer\n\n");
return 0;
}
This is a more user-friendly one I guess :
#include<stdio.h>
/* This program checks if the entered input is an integer
* or provides an option for the user to re-enter.
*/
int getint()
{
int x;
char c;
printf("\nEnter an integer (say -1 or 26 or so ): ");
while( scanf("%d",&x) != 1 )
{
c=getchar();
printf("You have entered ");
putchar(c);
printf(" in the input which is not an integer");
while ( getchar() != '\n' )
; //wasting the buffer till the next new line
printf("\nEnter an integer (say -1 or 26 or so ): ");
}
return x;
}
int main(void)
{
int x;
x=getint();
printf("Main Function =>\n");
printf("Integer : %d\n",x);
return 0;
}
I developed this logic using gets and away from scanf hassle:
void readValidateInput() {
char str[10] = { '\0' };
readStdin: fgets(str, 10, stdin);
//printf("fgets is returning %s\n", str);
int numerical = 1;
int i = 0;
for (i = 0; i < 10; i++) {
//printf("Digit at str[%d] is %c\n", i, str[i]);
//printf("numerical = %d\n", numerical);
if (isdigit(str[i]) == 0) {
if (str[i] == '\n')break;
numerical = 0;
//printf("numerical changed= %d\n", numerical);
break;
}
}
if (!numerical) {
printf("This is not a valid number of tasks, you need to enter at least 1 task\n");
goto readStdin;
}
else if (str[i] == '\n') {
str[i] = '\0';
numOfTasks = atoi(str);
//printf("Captured Number of tasks from stdin is %d\n", numOfTasks);
}
}
printf("type a number ");
int converted = scanf("%d", &a);
printf("\n");
if( converted == 0)
{
printf("enter integer");
system("PAUSE \n");
return 0;
}
scanf() returns the number of format specifiers that match, so will return zero if the text entered cannot be interpreted as a decimal integer
The way I worked around this question was using cs50.h library. So, the header goes:
#include <cs50.h>
There you have get_int function and you simply use it for variable initiation:
int a = get_int("Your number is: ");
If a user inputs anything but integer, output repeats the line "Your number is: "; and so on until the integer is being written.
I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.
#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function
#define TRUE 1
#define FALSE 0
int main(void)
{
char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
int intTest;
printf("Give me an int: ");
do
{
scanf(" %s", n);
intTest = TRUE; // Sets the default for the integer test variable to TRUE
int i = 0, l = strlen(n);
if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
i++;
while (i < l)
{
if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
{
intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
break;
}
i++;
}
if (intTest == TRUE)
printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
else
printf("Retry: "); // Prints "Retry:" if tested FALSE
}
while (intTest == FALSE); // Continues to ask the user to input a valid integer value
return 0;
}
Just check is your number has any difference with float version of it, or not.
float num;
scanf("%f",&num);
if(num != (int)num) {
printf("it's not an integer");
return;
}
This method works for everything (integers and even doubles) except zero (it calls it invalid):
The while loop is just for the repetitive user input. Basically it checks if the integer x/x = 1. If it does (as it would with a number), its an integer/double. If it doesn't, it obviously it isn't. Zero fails the test though.
#include <stdio.h>
#include <math.h>
void main () {
double x;
int notDouble;
int true = 1;
while(true) {
printf("Input an integer: \n");
scanf("%lf", &x);
if (x/x != 1) {
notDouble = 1;
fflush(stdin);
}
if (notDouble != 1) {
printf("Input is valid\n");
}
else {
printf("Input is invalid\n");
}
notDouble = 0;
}
}
I was having the same problem, finally figured out what to do:
#include <stdio.h>
#include <conio.h>
int main ()
{
int x;
float check;
reprocess:
printf ("enter a integer number:");
scanf ("%f", &check);
x=check;
if (x==check)
printf("\nYour number is %d", x);
else
{
printf("\nThis is not an integer number, please insert an integer!\n\n");
goto reprocess;
}
_getch();
return 0;
}
I found a way to check whether the input given is an integer or not using atoi() function .
Read the input as a string, and use atoi() function to convert the string in to an integer.
atoi() function returns the integer number if the input string contains integer, else it will return 0. You can check the return value of the atoi() function to know whether the input given is an integer or not.
There are lot more functions to convert a string into long, double etc., Check the standard library "stdlib.h" for more.
Note : It works only for non-zero numbers.
#include<stdio.h>
#include<stdlib.h>
int main() {
char *string;
int number;
printf("Enter a number :");
string = scanf("%s", string);
number = atoi(string);
if(number != 0)
printf("The number is %d\n", number);
else
printf("Not a number !!!\n");
return 0;
}