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).
问题是我不能使用atoi或其他类似的函数(我很确定我们应该依赖于数学运算)。
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?
什么好主意吗?
32
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).
num总是包含一个整数,因为它是一个整数。scanf返回已成功读取的项的数量,因此在这种情况下,它必须返回1作为有效值。如果没有,则输入一个无效的整数值,num变量可能不会被更改(也就是说,仍然有一个任意的值,因为您没有初始化它)。
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:
在您的评论中,您只希望允许用户输入一个整数,后跟enter键。不幸的是,scanf(“%d\n”)不能简单地实现这一点,但是这里有一个技巧:
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");
22
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
12
There are several problems with using scanf
with the %d
conversion specifier to do this:
使用%d转换说明符使用scanf有几个问题:
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;
如果输入字符串以一个有效整数(如“12abc”)开始,那么将从输入流中读取“12”,并将其转换为num,而scanf将返回1,因此当您(可能)不应该时,您将指示成功;
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;
如果输入字符串不以数字开头,那么scanf将不会从输入流中读取任何字符,num将不会被更改,返回值将为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.
您不指定是否需要处理非十进制格式,但如果必须处理八进制或十六进制格式(0x1a)的整数值,则不能这样做。%i转换说明符处理十进制、八进制和十六进制格式,但是仍然存在前两个问题。
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
首先,您需要将输入读取为字符串(最好使用fgets)。如果你不允许使用atoi,你可能也不允许使用strtol。因此,您需要检查字符串中的每个字符。检查数字值的安全方法是使用isdigit库函数(还有分别检查八进制和十六进制数字的isodigit和isxdigit函数),例如
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).
(如果你甚至都不允许使用isdigit、isodigit或isxdigit,那就扇你的老师/教授一巴掌,让你的作业比实际需要的更困难)。
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.
如果您需要能够处理八进制或十六进制格式,那么它会变得有点复杂。C的约定是八进制格式的首位为0,十六进制格式的首位为0x。因此,如果第一个非空格字符是0,您必须先检查下一个字符,然后才能知道使用哪种非十进制格式。
The basic outline is
的基本轮廓
isdigit
to check the remaining characters;isodigit
to check the remaining characters;x
or X
, then the input is in hexadecimal format and you will use isxdigit
to check the remaining characters;4
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
).
您将变量指定为类型integer,然后使用scanf,但只针对整数(%d)。
What else could it possibly contain at this point?
在这一点上它还可能包含什么?
0
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!
我查看了上面每个人的输入,这是非常有用的,并制作了一个适合我自己应用的函数。这个函数实际上只是评估用户的输入不是“0”,但它对我来说已经足够好了。希望这可以帮助!
#include
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) && (iUserInputiUpperBound)){
printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
iUserInput=0;
}
}
return iUserInput;
}
0
Try this...
试试这个…
#include
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;
}
0
This is a more user-friendly one I guess :
我想这是一个更友好的方法:
#include
/* 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;
}
0
I developed this logic using gets and away from scanf hassle:
我使用get and away from scanf麻烦开发了这个逻辑:
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);
}
}
0
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
scanf()返回匹配的格式说明符的数量,如果输入的文本不能解释为十进制整数,则返回0
-1
I was having the same problem, finally figured out what to do:
我遇到了同样的问题,终于想出了办法:
#include
#include
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;
}
-1
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.
我一直在寻找一个更简单的解决方案,只使用循环和if语句,这就是我想到的。该程序还可以处理负整数,并正确地拒绝任何可能包含整数和其他字符的混合输入。
#include
#include // Used for atoi() function
#include // 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 '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;
}
-1
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.
while循环仅用于重复的用户输入。它检查整数x/x是否等于1。如果它这样做(就像它对待数字那样),它就是一个整数/双精度数。如果没有,显然不是。Zero在测试中失败了。
#include
#include
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;
}
}
-2
I found a way to check whether the input given is an integer or not using atoi() function .
我找到了一种方法,可以使用atoi()函数检查给定的输入是否是整数。
Read the input as a string, and use atoi() function to convert the string in to an integer.
将输入读取为字符串,并使用atoi()函数将字符串转换为整数。
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.
函数的作用是:如果输入字符串包含整数,则返回整数,否则返回0。您可以检查atoi()函数的返回值,以知道给定的输入是否是整数。
There are lot more functions to convert a string into long, double etc., Check the standard library "stdlib.h" for more.
还有很多函数可以将字符串转换为长、双等,请查看标准库“stdlib”。h”。
Note : It works only for non-zero numbers.
注意:它只适用于非零数。
#include
#include
int main() {
char *string;
int number;
printf("Enter a number :");
scanf("%s", string);
number = atoi(string);
if(number != 0)
printf("The number is %d\n", number);
else
printf("Not a number !!!\n");
return 0;
}