I want to scan in a string that can take at least 200 characters and then I want to convert the string to an int, so that I can print it with e.g. printf("%d", digit).
How can I write a function kinda like this I've written here
(this one does not work!):
int main()
{
char car[200];
int number;
int i,x;
int sum = 0;
printf("Write in number: \n");
scanf("%c", &car);
for (i=0; i<200; i++) {
if (car[i] != '\0') {
x = car[i]-'0';
sum = sum + x;
if (i != 0) {
sum = sum*10;
}
}
}
return 0;
}
first:
scanf("%c", &car);
from man scanf:
c
Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer
must be a pointer to char, and there must be enough
room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To
skip white space first, use an explicit space
in the format.
So you're reading exactly one character, not a whole string.
Then, you rely on a terminating null byte being added, which isn't happening. Use %199s instead, leaving enough room for the terminating null byte.
Then, considering no int in this world should have enough space for numbers with 199 decimal digits, you should think about your 200 character buffer.
If your goal is not to write such a function for educational purposes, but because you need one:
int number;
scanf("%d", &number);
does exactly that: Read one number from the input, and place it in number.
scanf("%s", car);
You need to read a string %s not a single char %c. Also char array will decay to a pointer when passed as an argument, so you shouldn't use &char.
Here is the solution,Start from the end of the string because units place is from right to left then increment the units place to ten's place then 100 and so on.
#include<stdio.h>
#include<string.h>
int main()
{
char input[9];
int digit,number=0,i=1;
printf("Enter Number:\n");
scanf("%s",input);
digit=strlen(input)-1;
while(digit>=0)
{
number=number + i*(input[digit]-'0');
digit=digit-1;
i=i*10;
}
printf("%d",number);
return 0;
}
Close. Suggested changes below.
Use char car[200+1] to "take at least 200 characters".
Use "%200s" rather than "%c" to read a string rather than a char and to limit its input.
//int main()
int main(void) {
// char car[200];
char car[200+1];
int number;
int i,x;
int sum = 0;
printf("Write in number: \n");
// scanf("%c", &car);
scanf("%200s", car);
// for (i=0; i<200; i++) {
for (i=0; car[i]; i++) {
// if (car[i] != '\0'){
x = car[i]-'0';
// sum = sum + x;
sum = 10*sum + x;
// if (i != 0) { sum = sum*10; }
}
printf("%d\n", sum)
return 0;
}
Unless input is like "000000000000000000000000000123", 200 digits will certainly overflow sum.
To detect that
x = car[i]-'0';
if (sum >= INT_MAX/10 && (sum > INT_MAX/10 || x > INT_MAX%10)) {
x = INT_MAX;
// maybe set an error flag
break;
}
sum = 10*sum + x;
An int has an maximum value of INT_MAX from #include < limits.h>. It is at least 32767. Some platforms use 16-bit, 32-bit or 64-bit int Other ranges are possible. Let us assume a worst case of 128-bit. That would need about 39 decimal digits. Leaving room for a sign and terminating null character, suggest
char car[39+1+1];
Related
I have a number, 321197186 which the user inputs. How can I store this number into an array one element at a time. Basically, I am trying to store the 1st digit into 0th element and so on. And then I have to do some computation on that number.
Represent your number as a string, where every character of that string will be the corresponding digit of your number.
There are a plethora of method to read a string, but I suggest you use fgets() like this:
#include <stdio.h>
#include <string.h>
#define MAX_LEN 10
int main (int argc, char *argv[])
{
char number[MAX_LEN];
printf("Enter a number: \n");
fgets(number, MAX_LEN , stdin);
printf("%s\n", number);
return 0;
}
With a for loop, you access the characters (digits) of the string (number) one by one, if you like.
I suggest you also eat the trailing newline that fgets() leaves in the input array, as already explained in Removing trailing newline character from fgets() input.
Alternative solution proposed by bruno#:
scanf("%9s", number);
Read more in C - scanf() vs gets() vs fgets().
Assume you have
int num;
if (scanf("%d", &num) != 1)
{
// Input error
exit(1);
}
// Now the user input is available in num
then you do
#define MAX_DIGITS 32
int digits[MAX_DIGITS] = { 0 };
int index = 0;
while(num != 0 && index < MAX_DIGITS)
{
digits[index] = num % 10;
++index;
num = num / 10;
}
// Now the array digits holds the individual digits
// and index holds the number of valid digits
You can consider this logic in C -
number = 321197186
while(number> 0) - leave if number becomes 0
{
int last_digit = number % 10; - Last digit from the number
printf("%d",last_digit);
number = number / 10; - to get the remaining number.
}
This can be also done in Python as -
number = 321197186
list1 = []
for i in str(number):
list1.append(i)
print(list1)
store this number into an array one element at a time.
Let us take advantage of the input process to have a convenient way to determine the length of input including leading zeros (but not input with a sign, leading spaces) by using "%n" to record the offset of the scan.
Use % 10 to exact the least significant decimal digit of the number.
int number;
int offset;
if (scanf("%d%n", &number, &offset) == 1) {
int a[offset]; // VLA
while (offset > 0) {
a[--offset] = number % 10;
number /= 10;
}
for (int i = 0; i < sizeof a/sizeof a[0]; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
}
Output
a[0] = 3
a[1] = 2
a[2] = 1
a[3] = 1
a[4] = 9
a[5] = 7
a[6] = 1
a[7] = 8
a[8] = 6
But as bruno points out, you just have to check it as a string as an user input with fgets is an array of characters (even if we are talking about numbers).
For more detail:
for(i=0;i<sizeof(array_input);i++){
//Store the char into another array
}
I'm writing a code a that prompts the user to enter a string
&
create a function that is a type void that prints out the character that was used the most
(As in where it appeared more than any other ones)
&
also shows the number of how many times it was in that string.
Therefore here is what I have so far...
#include <stdio.h>
#include <string.h>
/* frequent character in the string along with the length of the string (use strlen from string.h – this will require you to #include <string.h> at the top of your program).*/
/* Use array syntax (e.g. array[5]) to access the elements of your array.
* Write a program that prompts a user to input a string,
* accepts the string as input, and outputs the most
* You should implement a function called mostfrequent.
* The function prototype for mostfrequent is: void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts);
* Hint: Consider the integer value of the ASCII characters and how the offsets can be translated to ints.
* Assume the user inputs only the characters a through z (all lowercase, no spaces).
*/
void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts_)
{
int array[255] = {0}; // initialize all elements to 0
int i, index;
for(i = 0; most_freq[i] != 0; i++)
{
++array[most_freq[i]];
}
// Find the letter that was used the most
qty_most_freq = array[0];
for(i = 0; most_freq[i] != 0; i++)
{
if(array[most_freq[i]] > qty_most_freq)
{
qty_most_freq = array[most_freq[i]];
counts = i;
}
num_counts_++;
}
printf("The most frequent character was: '%c' with %d occurances \n", most_freq[index], counts);
printf("%d characters were used \n", num_counts_);
}
int main()
{
char array[5];
printf("Enter a string ");
scanf("%s", array);
int count = sizeof(array);
mostfrequent(count , array, 0, 0);
return 0;
}
I'm getting the wrong output too.
output:
Enter a string hello
The most frequent character was: 'h' with 2 occurances
5 characters were used
should be
The most frequent character was: 'l' with 2 occurances
5 characters were used
let's do it short (others will correct me if I write something wrong ^_^ )
you declare a int like this:
int var;
use it like this :
var = 3;
you declare a pointer like this :
int* pvar;
and use the pointed value like this:
*pvar = 3;
if you declared a variable and need to pass a pointer to it as function parameters, use the & operator like this :
functionA(&var);
or simply save its address in a pointer var :
pvar = &var;
that's the basics. I hope it will help...
The function prototype you are supposed to use seems to include at least one superfluous parameter. (you have the total character count available in main()). In order to find the most frequently appearing character (at least the 1st of the characters that occur that number of times), all you need to provide your function is:
the character string to be evaluated;
an array sized so that each element represents on in the range of values you want to find the most frequent (for ASCII characters 128 is fine, for all in the range of unsigned char, 256 will do); and finally
a pointer to return the index in your frequency array that holds the index to the most frequently used character (or the 1st character of a set if more than one are used that same number of times).
In your function, your goal is to loop over each character in your string. In the frequency array (that you have initialized all zero), you will map each character to an element in the frequency array and increment the value at that element each time the character is encountered. For example for "hello", you would increment:
frequency['h']++;
frequency['e']++;
frequency['l']++;
frequency['l']++;
frequency['o']++;
Above you can see when you are done, the element frequency['l']; will hold the value of 2. So when you are done you just loop over all elements in frequency and find the index for the element that holds the largest value.
if (frequency[i] > frequency[most])
most = i;
(which is also why you will get the first of all characters that appear that number of times. If you change to >= you will get the last of that set of characters. Also, in your character count you ignore the 6th character, the '\n', which is fine for single-line input, but for multi-line input you need to consider how you want to handle that)
In your case, putting it altogether, you could do something similar to:
#include <stdio.h>
#include <ctype.h>
enum { CHARS = 255, MAXC = 1024 }; /* constants used below */
void mostfrequent (const char *s, int *c, int *most)
{
for (; *s; s++) /* loop over each char, fill c, set most index */
if (isalpha (*s) && ++c[(int)*s] > c[*most])
*most = *s;
}
int main (void) {
char buf[MAXC];
int c[CHARS] = {0}, n = 0, ndx;
/* read all chars into buf up to MAXC-1 chars */
while (n < MAXC-1 && (buf[n] = getchar()) != '\n' && buf[n] != EOF)
n++;
buf[n] = 0; /* nul-terminate buf */
mostfrequent (buf, c, &ndx); /* fill c with most freq, set index */
printf ("most frequent char: %c (occurs %d times, %d chars used)\n",
ndx, c[ndx], n);
}
(note: by using isalpha() in the comparison it will handle both upper/lower case characters, you can adjust as desired by simply checking upper/lower case or just converting all characters to one case or another)
Example Use/Output
$ echo "hello" | ./bin/mostfreqchar3
most frequent char: l (occurs 2 times, 5 chars used)
(note: if you use "heello", you will still receive "most frequent char: e (occurs 2 times, 6 chars used)" due to 'e' being the first of two character that are seen the same number of times)
There are many ways to handle frequency problems, but in essence they all work in the same manner. With ASCII characters, you can capture both the most frequent character and the number of times it occurs in a single array of int and an int holding the index to where the max occurs. (you don't really need the index either -- it just save looping to find it each time it is needed).
For more complex types, you will generally use a simple struct to hold the count and the object. For example if you were looking for the most frequent word, you would generally use a struct such as:
struct wfreq {
char *word;
int count;
}
Then you simply use an array of struct wfreq in the same way you are using your array of int here. Look things over and let me know if you have further questions.
Here is what I came up with. I messed up with the pointers.
void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts_)
{
*qty_most_freq = counts[0];
*most_freq = 'a';
int i;
for(i = 0; i < num_counts_; i++)
{
if(counts[i] > *qty_most_freq)
{
*qty_most_freq = counts[i];
*most_freq = 'a' + i;
}
}
}
/* char string[80]
* read in string
* int counts[26]; // histogram
* zero counts (zero the array)
* look at each character in string and update the histogram
*/
int main()
{
int i;
int num_chars = 26;
int counts[num_chars];
char string[100];
/*zero out the counts array */
for(i = 0; i < num_chars; i++)
{
counts[i] = 0;
}
printf("Enter a string ");
scanf("%s", string);
for(i = 0; i < strlen(string); i++)
{
counts[(string[i] - 'a')]++;
}
int qty_most_freq;
char most_freq;
mostfrequent(counts , &most_freq, &qty_most_freq, num_chars);
printf("The most frequent character was: '%c' with %d occurances \n", most_freq, qty_most_freq);
printf("%d characters were used \n", strlen(string));
return 0;
}
I'm currently doing the CS50 course, and I'm stuck on the credit problem. The idea is to make a program to verify cards due to their inbuilt checksum. The first step is to take every second digit and multiply it by 2, then add all the digits of the products together.
My code isn't finished, but I've set it up to print some intermediary steps just so I can see what's going on.
#include <stdio.h>
#include <string.h>
void checksum (char number[20]);
int main (void){
char *card;
printf("Please enter a card number:");
scanf("%s", card);
if (strlen(card) == 13 || strlen(card) == 16 || strlen(card) == 15) {
checksum(card);
}
else{
printf("Not a number. Please try again.\n");
main();
}
}
void checksum (char *number) {
int check = 0;
int digits = 0;
for(int i = 1; i < 17; i += 2){
printf("No%c\n", number[i]);
digits = (number[i] * 2);
printf("D%i\n", digits);
while (digits > 0) {
check += digits % 10;
printf("C%i\n", check);
digits = digits / 10;
}
}
}
I know the first part is far from perfect but it's the checksum function I'm concerned with at the moment. When it takes the second digit(5) everything is fine. But then when it's multiplied by 2 according to the next line, somehow the result is 106(?)
Can someone explain what's going on here?
terminal output
You read in a string, i.e. a sequence of characters, probably in ASCII format. So your input "1500150015001500" is actually a sequence of characters terminated by string terminating character 0x0, e.g. like { '1', '5', '0', .... '\0' }. A single character value like '1', when interpreted as an integral value, is represented by its ASCII code, which is 48 for '0', 49 for '1', ... , and 53 for '5'. Hence, an expression like char c = '5'; int digit = c*2 actually yields 106 for digit. To take character '5' as integral value 5, you could write int digit = (c - '0'), which is the same as if you wrote (53 - 48).
Without modifying your code to much, test what happens:
#include <stdio.h>
#include <string.h>
void checksum (char *number);
int main (void){
char card[30];
printf("Please enter a card number:");
scanf("%s", card);
if (strlen(card) == 13 || strlen(card) == 16 || strlen(card) == 15) {
checksum(card);
}
else{
printf("Not a number. Please try again.\n");
main();
}
}
void checksum (char *number) {
int check = 0;
int digits = 0;
for(int i = 1; i < strlen(number); i += 2){
printf("No%c\n", number[i]);
digits = ((number[i]-'0') * 2);
printf("D%i\n", digits);
while (digits > 0) {
check += digits % 10;
printf("C%i\n", check);
digits = digits / 10;
}
}
}
A couple of things:
char *card; scanf("%s", card); is not going to work. You need to either declare card as an array of fixed size (i.e. char card[20]), or use malloc to allocate memory for the pointer char *card;. If you choose the latter option you also need to use free on the memory when you're done with it.
In your function checksum, you need to convert the characters you read in the string card into numbers. If the character set on your system is ASCII, you can achieve this by subtracting the value 0x30 (i.e. the numeric value of the character '0') from each character in the string before performing arithmetic on it.
char number[20] in a function signature is pointless; see this question for more information. Since the array decays to a pointer to its first element when passed as a function argument, you may as well have char *number in the function signature.
I want to write a C program which will take an IP address from the user like "112.234.456.789" in a string and give formatted output in addition of each block in string, e.g., "04.09.15.24" for the above IP address. Here's what I have so far:
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
char s[15],d[11];
int i=0,c = 0, sum[4] = {0};
d[i]=sum[c]/10;
printf("Enter ip address:");
gets(s);
printf("\n \n %s",s);
i=0;
for(c=0;c<15;c++)
{
if(s[c]!='.'||s[c]!='\0')
sum[i]=(s[c]-48)+sum[i];
else
i++;
}
for(i=0,c=0;c<4;c++,i+=3)
{
d[i]=(sum[c]/10)+48;
d[i+1]=sum[c]%10+48;
d[i+2]='.';
}
printf("\n \n %s",d);
getch();
}
The input should be an IP address like "112.234.546.234", and the output should be the result of adding the digits in each block, "04.09.15.06". The input and output should be in strings.
The problem with your code is that s[c]!='.'||s[c]!='\0' is going to evaluate true for any character in the input -- even '.'. This means i is never incremented, and ot only is every digit is summed to sum[0], but so is '.' - 48.
What you meant was s[c] != '.' && s[c] != '\0'.
I wrote the function you desire here.
#include <stdio.h>
#include <ctype.h>
void convert(const char *in, char *out) {
unsigned int sum = 0;
char ch;
do {
ch = *in++;
if (isdigit(ch)) {
sum += ch - '0';
} else {
*out++ = sum / 10 + '0';
*out++ = sum % 10 + '0';
if (ch == '.') {
*out++ = '.';
sum = 0;
}
}
} while (ch);
}
By the way, each "block" of the IPv4 address is an octet, and what you are doing is replacing each with its digit sum.
I just code you a simple example of how to "discard" unwanted characters.
#include <studio.h>
main ()
{
int add1, add2, add3, add4;
printf("enter an ip in the form xxx.xxx.xxx.xxx: )";
scanf("%d%*c%d%*c%d%*c%d", &add1, &add2, &add3, &add4);
printf("add1 = %d add2 = %d add3 = %d add4 = %d\n\n", add1, add2, add3, add4);
return 0;
}
console output:
enter a ip in the form xxx.xxx.xxx.xxx: 123.321.456.654
add1 = 123 add2 = 321 add3 = 456 add4 = 654
EDIT: you just have to play along with the "add#" variables to do your math thing.
It looks like homework (if this is the case, please tag it as homework), so I am going to give a few pointers:
Use fgets to read the input from the user. Read the input into a string.
Use sscanf to parse the string. Since you know there will be four positive integers, use "%u.%u.%u.%u" as the format string.
For each one of the four integers, compute the sum of the digits (using division by 10 and remainder by 10, as you just did).
Print the formatted output using printf (or snprintf to print to a string). If you want each sum to be formatted as a two-digits integer, with leading 0, use "%02u" as format specifier.
P.S. Be careful with snprintf, it might bite.
Other tips
Focus on one step at a time. Divide and conquer. Write a digit_sum function, taking an integer as argument, which computes the sum of its digits:
unsigned int digit_sum(unsigned int n)
{
unsigned int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
Once your digit_sum function is working well, proceed with the main task.
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;
}