我的问题是在没有按回车的情况下尝试转到下一条指令..这是我的代码
cout<<"Enter Date Of Birth: ";
cin>>day;
cout<<"/";
cin>>month;
cout<<"/";
cin>>year;
只提供一天的2位数字,我希望下一条指令在没有按下回车的情况下打印,所以进入休息月份和年份。由于年份是最后一年,我可以在此之后按下输入。
答案 0 :(得分:1)
你可以写一个这样的函数:
#include <iostream>
#include <sstream>
#include <conio.h>
#include <vector>
#include <math.h>
int getInput(int count)
{
int i = 0;
std::stringstream ss;
while (count)
{
char c = _getch();
std::cout << c;
ss << c;
count--;
}
ss >> i;
return i;
}
int getInput_(int count)
{
int num = 0;
std::vector <int> v;
while (count)
{
char c = _getch();
std::cout << c;
v.push_back(atoi(&c));
count--;
}
for (size_t i = 0; i < v.size(); i++)
{
num += (int)(v[i] * (pow((float)10, (float)(v.size()-1)-i)));
}
return num;
}
int main()
{
int day = 0, month = 0, year = 0;
day = getInput_(2);
std::cout << "/";
month = getInput_(2);
std::cout << "/";
year = getInput_(4);
std::cout << std::endl << day << "/" << month << "/" << year;
}
答案 1 :(得分:1)
这在纯C ++中是不可能的,因为它过分依赖于可能与stdin连接的终端(它们通常是行缓冲的)。但是,你可以使用一个库:
如果您的目标是跨平台兼容性,我建议您使用curses。也就是说,我确信有一些功能可以用来关闭线路缓冲(我相信这叫做“原始模式”,而不是“煮熟模式”(看看man stty))。如果我没弄错的话,诅咒会以便携的方式为你处理。
答案 2 :(得分:0)
你需要做两件事。
一,使用对计数字符数而不是空格分隔符进行操作的输入函数。这排除了所有流提取运算符,您无法使用cin >> anything
。
然后,将终端模式从“cooked”更改为“raw”。当终端处于熟制模式时,在按下输入之前,不会向您的程序传送任何字符。执行此操作的方法取决于您没有告诉我们的操作系统。请注意,这也会阻止终端为您处理编辑键(如退格键),因此如果您想支持它们,您必须自己编写该逻辑代码。
答案 3 :(得分:0)
对于linux,下面的代码可以实现你想要的(引用你应该阅读的这个SO线程Capture characters from standard input without waiting for enter to be pressed):
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <termios.h>
using namespace std;
char getch(void) {
char buf = 0;
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if (read(0, &buf, 1) < 0)
perror ("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror ("tcsetattr ~ICANON");
return (buf);
}
void readn(char *data, int N) {
for(int ii = 0; ii < N; ii++) { data[ii] = getch(); cout << data[ii]; cout.flush(); };
};
int main () {
char day[2], month[2], year[4];
cout<<"Enter Date Of Birth: "; cout.flush();
readn(day, 2); cout << "/"; cout.flush();
readn(month, 2); cout << "/"; cout.flush();
readn(year, 4); cout << endl; cout.flush();
}