我有以下程序:
int main(int argc, char *argv[])
{
int a, b;
char c1, c2;
printf("Enter something: ");
scanf("%d",&a); // line 1
printf("Enter other something: ");
scanf("%d", &b); // line 2
printf("Enter a char: ");
scanf("%c",&c1); // line 3
printf("Enter another char: ");
scanf("%c", &c2); // line 4
printf("Done"); // line 5
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如我在C书中读到的那样,作者说scanf()
在缓冲区中留下了一个新的行字符,因此,程序不会在第4行停止供用户输入数据,而是将新行字符存储在c2中并移至第5行.
是对的吗?
但是,这只发生在char
数据类型中吗?因为我没有int
在第1,2,3行中看到数据类型的这个问题.是不是?
我倾向于C编程.我写了一个奇怪的循环,但在我使用%c
时不起作用scanf()
.
这是代码:
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
scanf("%c", &another);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我%s
在这段代码中使用scanf("%s", &another);
,那么它工作正常.
为什么会这样?任何的想法?
这可能是一个简单的问题,但我搜索了很多,仍然没有想出来.我用gcc编译下面的剪辑代码并从终端运行程序.在正确的情况下,它允许输入int和char,但它不允许.它不等待进入char?
这里的任何人都可以帮助我.提前致谢!
#include <stdio.h>
int main()
{
char c;
int i;
// a
printf("i: ");
fflush(stdin); scanf("%d", &i);
// b
printf("c: ");
fflush(stdin); scanf("%c", &c);
return 0;
Run Code Online (Sandbox Code Playgroud)
}
以下是我的源代码.读完整数后,程序应该等到我键入一个字符串然后按回车键.但是,只要我输入整数,程序就会退出.你能告诉我我的错吗?
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char command[255];
scanf("%d", &n);
fgets(command, 255, stdin);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我提到我也尝试使用gets(command)
,但我得到了相同的结果.
给出以下代码:
#include <stdio.h>
int main()
{
int testcase;
char arr[30];
int f,F,m;
scanf("%d",&testcase);
while(testcase--)
{
printf("Enter the string\n");
fgets(arr,20,stdin);
printf("Enter a character\n");
F=getchar();
while((f=getchar())!=EOF && f!='\n')
;
putchar(F);
printf("\n");
printf("Enter a number\n");
scanf("%d",&m);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望用户输入一个字符串、一个字符和一个数字,直到测试用例变为零。
我的疑虑/疑问:
1.用户无法输入字符串。看来fgets
不行。为什么?
2.如果我使用scanf
而不是fgets
,则getchar
无法正常工作,即我在其中输入的任何字符都putchar
作为新行。为什么?
谢谢您的帮助。
我想按格式"%d:%c"输入数据
我有这个:
#include <stdio.h>
int main() {
int number;
char letter;
int i;
for(i = 0; i < 3; i ++) {
scanf("%c:%d", &letter, &number);
printf("%c:%d\n", letter, number);
}
}
Run Code Online (Sandbox Code Playgroud)
我期待这个:
Input: "a:1"
Output: "a:1"
Input: "b:2"
Output: "b:2"
Input: "c:3"
Output: "c:3"
Run Code Online (Sandbox Code Playgroud)
但是我的程序做了这样的事情:
a:1
a:1
b:2
:1
b:2
--------------------------------
Process exited with return value 0
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
这里有什么问题?