#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *method1(void)
{
static char a[4];
scanf("%s\n", a);
return a;
}
int main(void)
{
char *h = method1();
printf("%s\n", h);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,提示符要求我两次输入(我只scanf在代码中使用一次).这是为什么?
(我输入'jo';它要求更多输入,所以我再次输入'jo'.然后它只打印出'jo'一次.)
我正在尝试: - 如果用户输入无效值,则重新读取该值.但问题只scanf()执行一次,不会执行任何其他时间,程序会陷入无限循环.
#include<stdio.h>
#include<math.h>
main()
{
unsigned int a;
unsigned int b = pow(2,M-1);
unsigned int c;
int x;
printf("b = %i",b);
input:
fflush(stdin);
fflush(stdout);
printf("\nEnter any integer: ");
x = scanf("%u",&a);
printf("%u",a);
if(x==0)
goto input;
printf("\na = %i",a);
c = a & b;
printf("\nc = %i",c);
if(c)
printf("\nthe bit %i is set",M);
else
printf("\nthe bit %i is not set",M);
}
Run Code Online (Sandbox Code Playgroud)
我之前尝试使用添加空间,但%u也试过fflush(stdin)但没有任何效果.
编辑:我知道不建议使用goto,但我必须这样做.(使用循环不是一个选项).M是我在编译时使用gcc命令行定义的宏.
我正在用C开发一款国际象棋游戏,仅仅是为了练习.在游戏开始时,用户可以键入4个内容:
<whitespace>COL(即2 2)我如何使用a scanf期望2个整数或1个字符?
码:
printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
scanf("%c", &matrix2[i][j]);
compress(matrix2);
break;
Run Code Online (Sandbox Code Playgroud)
我的代码假设采用5 x 10char矩阵.但是目前我的换行符正在输入到矩阵中,我如何实际检查换行符,并防止它进入matrix2[i][j]?
它总共读取了4个换行符.输入:
aaabbbcccd (press enter)
ababababab (press enter)
bcdbcdbcdb (press enter)
ababababab (press enter)
abbbcccdda
Run Code Online (Sandbox Code Playgroud) 我是C编程的初学者,我有一个问题.我将以一个简单的代码为例:
#include <stdio.h>
int main( void )
{
int x;
printf( "Please type the number 10." );
scanf( "%i\n", &x );
if ( x == 10 )
printf( "Thank you!\n" );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,当我编译并运行该程序时,我的终端显示以下消息:
"Please type the number 10."
Run Code Online (Sandbox Code Playgroud)
然后它等待输入,所以我输入它要求的数字(10),然后按ENTER.问题是,在我按ENTER一次后,它会移动到一个新行并等待更多输入.只有在输入10并再次按下ENTER后才能继续(...显示"谢谢!").
所以看来我必须按ENTER两次才能接受我的输入.有谁知道为什么会这样?