如何在 c++ 中在同一行上输入
How to take input on same line in c++?
我想以这种格式输入日期 2/11/2015。 我如何使用 C++?谢谢 以下方法不起作用。
cin>>day >>month >>year ;
而且用户也不必按回车键。
我的代码是
#include <iostream>
using namespace std;
class Date
{
private :
int day,month,year;
char slash;
public :
void inputdate(void)
{
cout<<"Enter Date in Formate (day/month/year)"<<endl;
cin >> day >> slash >> month >> slash >> year;
}
void checkdate(void)
{
if (day<=0 || day>=32)
{
cout<<"Day is Wrong ! "<<endl;
}
if (month==2 && day>=29)
{
cout<<"February can have max 28 days !"<<endl;
}
if (month<=0 || month>=13)
{
cout<<"Month is wrong !"<<endl;
}
if (year<=1799 || year>=3000)
{
cout<<"Year is Wrong !"<<endl;
}
if ((month==4 || month==6 || month==9 || month==11)&&(day>30))
{
cout<<"Day is wrong ! September ,April ,June and November can have maximum 30 days ."<<endl;
}
}
void showdate(void)
{
checkdate();
cout<<"Date is : "<<day<<"/"<<month<<"/"<<year<<endl;
}
};
C++本身并不
理解文本日期;您需要使用提供此功能的库,或者自己创建一个函数来在文本格式和内部整数格式之间进行转换(通常是自"纪元"(1970 年 1 月 1 日 00:00(以来的秒数或毫秒数,具体取决于平台(。
为此,您需要:
- 将日期收集为单个字符串或字符数组
- 将日期分隔为其组成日/月/年
- 将此日期计算为自纪元以来的秒数
说了这么多,使用库的第一个选项可能是最好的,因为它还将包含字符串和内部日期格式之间切换的功能;你选择哪个库取决于你,很大程度上取决于你编码的平台。
您可以使用
虚拟char
变量读取/
分隔符:
int day, month, year;
char slash; // dummy to skip past the '/'
cin >> day >> slash >> month >> slash >> year;
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在C++中,我如何接受不同于同一行的用户输入
- 如何确保用户在一行上提示输入一次时输入名字和姓氏?
- 忽略一行输入中的某些输入
- 丢失读入的每一行输入中的最后一个令牌
- 一行输入到多个变量
- 如何检查从键盘输入的特定整数值是否存在于C++文件中的一行或多行中
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 与 C++ 中一行中的用户输入数组元素相关的问题
- 如何在应用程序进行大量printf时,在固定输入的终端中设置最后一行
- 使用 getline 从输入文件读取一行到输出文件
- 标准输入未读取最后一行
- C :使用getline从文本文件中输入,要么跳过第一行,要么将其余部分弄乱
- 在C++的同一行输入值
- 使用 Getline C++ 将每一行输入存储在数组中
- scanf() 为最后一行输入提供错误的输出
- 如何在只有一行输入的向量中输入多个输入
- 仅对前一行输入使用cin.clear()或cin,ignore()
- 我如何在同一行输入2个不同的变量,同时使用setw进行格式化