使用 CIN 提示并接收日期"MM/DD/YYYY",忽略"/"字符?(C++)
Prompt for and receive a date "MM/DD/YYYY" using CIN, ignoring the "/" characters? (in C++)
是的,这是一个作业。我不介意为了得到答案而工作,我不想要确切的答案!这是我第一次上c++课。我是带着对VBA、MySql、CSS和HTML的先验知识来上这门课的。
我们被要求编写一个包含几个不同函数的程序。其中一个需要接收 "MM/DD/YYYY"
格式的日期输入。虽然这本身很容易;作为初学者,我只需要输入
cin >> month >> day >> year;
并在返回给用户时插入"/"。
然而,我相信我们的教授希望用户准确地输入日期"12/5/2013",或任何其他日期。
按照他的指示:
'/'
可以通过cin读取。因此,阅读'/'
字符并忽略它。将日设置为第三个输入,将月设置为第一个输入,将年设置为第五个输入。丢弃第二个和第四个输入
^这就是我偏离航向的地方。
我将非常感谢任何帮助!
编辑:我已经在这里寻找了答案,但是我遇到的所有答案都超出了我们所教的范围,因此不允许在作业中出现。虽然我可以很容易地理解更高级编码的逻辑,但我对自己缺乏轻松解决这些简单问题的能力感到沮丧。因此我在这里发帖。我花了几个小时浏览我们的教科书,寻找可能的答案或"忽略"输入字符串中的字符的线索,但没有找到。
这其实很简单!问题是:你可以输入不止一个东西。这意味着,如果您写入int d; std::cin >> d;
,则完全可以输入30/06/2014
。d
的值变成了30
,其余的输入还没有被读取。如果您编写下一个std::cin
语句,则可用的内容是/06/2014
。
然后需要消耗/
,读取月份,再次消耗,最后读取年份。
#include <iostream>
int main()
{
int d;
int m;
int y;
std::cin >> d; // read the day
if ( std::cin.get() != '/' ) // make sure there is a slash between DD and MM
{
std::cout << "expected /n";
return 1;
}
std::cin >> m; // read the month
if ( std::cin.get() != '/' ) // make sure there is a slash between MM and YYYY
{
std::cout << "expected /n";
return 1;
}
std::cin >> y; // read the year
std::cout << "input date: " << d << "/" << m << "/" << y << "n";
}
如果你能保证输入格式是正确的,那么直接写
就可以了std::cin >> d;
std::cin.get();
std::cin >> m;
std::cin.get();
std::cin >> y;
或者,如果你不习惯使用std::cin.get()
,它就像读取一个字符一样好:
char slash_dummy;
int d;
int m;
int y;
std::cin >> d >> slash_dummy >> m >> slash_dummy >> y;
下面是一些示例:
- 带有错误检查的代码 <
- 忽略错误/gh>
- 不含
std::cin.get()
遵循以下伪代码:
declare a char pointer to accept input
declare int to use as day, month and year
initialize day, month and year to 0
declare a int count to know what number you are up to
read `cin` operation into your input
increment through the input, stop if the current input position is NULL
read out character
if character != "/"
if count == 0
if month == 0
month = (int)character
else
month = month * 10 + (int)character
endif
else
if count == 1
if day == 0
day = (int)character
else
day = day * 10 + (int)character
endif
else
if year < 1000
year = year * 10 + (int)character
endif
endif
endif
else count += 1 endif
为什么不使用stringstreams呢?
string input;
int year, month, day;
cin >> input; // input can be 2005:03:09 or 2005/04/02 or whatever
stringstream ss(input);
char ch;
ss >> year >> ch >> month >> ch >> day;
- c++字符串中的字符将被忽略
- 如何忽略输入流中的某些字符?
- 如何在 getline 中删除/忽略超过特定数字的字符?
- 如何忽略第一个字符输入后的所有内容
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- 对c++中的输入使用getline函数时忽略第一个字符
- 如何告诉字符串流忽略null终止字符
- C++如何通过忽略每行的第一个字符来读取 unicode 文件
- For 循环字符串忽略字符
- 如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *
- 如何替换/忽略 C stdio.h getline() 中的无效 Unicode/UTF8 字符
- 为什么std :: istream ::忽略丢弃字符
- 忽略给定单词之前的所有字符
- 如何忽略除第一个字符之外的所有字符
- C++ 如何从用户输入中读取第一个字符并忽略 rest(字符类型)
- 为什么在使用循环时忽略输入的第一个字符
- 输入字符时忽略回车键
- 从文件中读取输入时,C 忽略字母字符
- 如何将SSCANF()设置为在字符串开始时忽略字符
- 通过HTTP获得C ,忽略Char缓冲区中的逃生字符