我在单击运行时构建了它,没有任何错误,没有警告也没有显示任何内容
#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char name[20], address[30];
char c;
printf("put your pass key: ");
c = getchar();
printf("Enter your name: ");
scanf("%s",name);
printf("Enter your address: ");
scanf("%s",address);
printf("--------------------------\n");
printf("Entered Name: %s\n",name);
printf("Entered Address: %s\n",address);
printf("Your pass key: ");
putchar(c);
}
我试图从通过关键点运行它,但是它可以正常工作,但是当我继续时,却没有任何帮助
答案 0 :(得分:0)
我已经编译了您的代码,对我来说很好用。一切都很好。也许您提供的输入值格式不正确。
答案 1 :(得分:0)
该代码运行良好。 Check your results here.
正如rng70所说,请重新检查您的输入值。另外,如果您要在string
输入之间添加空格,则该行将不起作用,因为默认情况下空白充当scanf()
的定界符。
很抱歉!
准确地说,如果这是您的错误,则空格后的字符不被视为strings
的输入。
要解决该问题,您可以使用scanf("%[^\n]", name);
答案 2 :(得分:0)
不幸的是,我不确定我是否正确理解了您的问题。
但是,在Linux下,该程序可以通过以下方式工作:
闭上眼睛,假设程序正确运行并键入。您将看到:
put your pass key: KMartin
Enter your name: Enter your address: Hello
--------------------------
Entered Name: Martin
Entered Address: Hello
Your pass key: K
为什么?
在Linux中键入某些键时,操作系统会将按下的键存储在某个缓冲区中,直到按下“输入”(“返回”)键为止。
也许MINGW具有相同的行为。
因此程序到达getchar()
,然后键入“ K”“ M”“ a”“ r”“ t”“ i”“ n”。
Linux将这些密钥存储在缓冲区中,而不是将这些密钥传递给程序。
我按“输入”(“返回”)键。然后,Linux将把“ K”传递给getchar()
函数,并将其余键(“马丁”)传递给scanf()
函数。
可以禁用此行为:
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
int main(void) {
char name[20], address[30];
char c;
struct termios tios;
printf("put your pass key: ");
/* Disable the buffer */
tcgetattr(1,&tios);
tios.c_lflag&=~ICANON;
tios.c_cc[VTIME]=0;
tios.c_cc[VMIN]=1;
tcsetattr(1,TCSANOW,&tios);
c = getchar();
/* Re-enable the buffer
* If the buffer is not enabled,
* sscanf() won't work correctly. */
tios.c_lflag|=ICANON;
tcsetattr(1,TCSANOW,&tios);
printf("\nEnter your name: ");
...
...,输出将是:
put your pass key: K
Enter your name: Martin
Enter your address: Hello
--------------------------
Entered Name: Martin
Entered Address: Hello
Your pass key: K
编辑
我在eclipse上运行它,但什么也没显示,但是当使用@ user366312之类的repl时,它在eclipse的控制台中看不到任何东西
Eclipse中的控制台通常不允许输入,因此程序可以写输出但不能接收输入。
但是,我知道有一些复选框(至少在某些Eclipse版本中)允许输入...
我不知道您在使用Eclipse时是否会遇到上述问题。
但是,如果您有这种行为,则settermios
方法可能行不通...