#include <stdio.h>
#define SIZE 5
void func(int*);
int main(void)
{
int i, arr[SIZE];
for(i=0; i<SIZE; i++)
{
printf("Enter the element arr[%d]: ", i);
scanf("%d", &arr[i]);
}//End of for loop
func(arr);
printf("The modified array is : ");
for(i=0; i<SIZE; i++)
printf("%d ", arr[i]);
return 0;
}
void func(int a[])
{
int i;
for(i=0; i<SIZE; i++)
a[i] = a[i]*a[i];
}
Run Code Online (Sandbox Code Playgroud)
输出:::

当我输入整数元素时输出是OK.但是当我输入一个像1.5这样的浮点值时,它没有要求其他元素,而O/P如图所示.我认为它应该隐式地将类型转换为1.5 1但它没有发生..你能告诉我为什么会这样吗?有关编译器的所有信息如图所示.
当您扫描scanf("%d")的值1.5将停在小数点并返回1时.
在接下来的调用时scanf,指针将仍然指向小数点,因为没有数字有扫描您的扫描将立即返回.
您应该检查返回值scanf- 它为您提供成功扫描的项目数,最初为1小数点前1 ,从0 开始为0.
顺便说一句,scanf代表"扫描格式化",我保证你找不到比用户输入更多未格式化的内容.
调查寻找fgets线路输入.这是我经常用于此目的的函数的副本:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
Run Code Online (Sandbox Code Playgroud)
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
一旦你开始使用该功能,你可以sscanf根据自己的内容,更轻松地处理错误.