我在C编程,并对此感到疑惑。 让我们说这是一个简单的程序:
Username:
Password:
现在......看起来简单,打印简单,所有(printf("Username: \nPassword: ");
)
但是如何获取用户名字符串?当然fgets但是...我希望用户在“用户名:”之后输入,而不是在密码之后输入。您可以预先printf("\b");
删除以前写入的数据在同一行,但如何才能找到“用户名:”?删除“密码:”后,“\ b”无效,显然与回车相同。我该怎么做?
答案 0 :(得分:3)
如果这是Windows,您可以像这样移动光标:
#include <stdio.h>
#include <windows.h>
void setCursorPos(int x, int y)
{
HANDLE hStdout;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout, &csbiInfo);
csbiInfo.dwCursorPosition.X = x;
csbiInfo.dwCursorPosition.Y = y;
SetConsoleCursorPosition(hStdout, csbiInfo.dwCursorPosition);
}
int _tmain(int argc, _TCHAR* argv[])
{
system("cls");
char user[128], pass[128];
printf("Username:\r\nPassword:\r\n");
setCursorPos(10, 0);
fgets(user, 128, stdin);
setCursorPos(10, 1);
fgets(pass, 128, stdin);
printf("User = %s, Pass = %s\r\n", user, pass);
return 0;
}
答案 1 :(得分:2)
尝试例如here所描述的终端转义序列,并得到大多数终端的支持。它们允许在屏幕上移动光标和类似的效果。如果这是一个很好的起点,请检查以下代码。
#include <stdio.h>
int main(){
printf("Username: \nPassword: \n");
printf("\033[2A\033[10C"); // move cursor 2 lines up, 10 chars right.
fflush(stdout);
getchar();
// ... continue your reading, moving, ...
}
答案 2 :(得分:1)
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(){
char username[64];
char password[16];
int ch, i = 0;
printf("Username:");
scanf("%63[^\n]%*c", username);
printf("Password:");
while((ch=getch())!='\r' && i < 16-1){
putchar('*');
password[i++]= ch;
}
password[i] = '\0';
if(strcmp(password, "drowssap")==0)
printf("\nOK\n>");
return 0;
}
答案 3 :(得分:0)
或者只是
printf("Username:");
/* do stuff */
printf("Password:");
/* do stuff */