使用 CIN 提示并接收日期"MM/DD/YYYY",忽略"/"字符?(C++)



是的,这是一个作业。我不介意为了得到答案而工作,我不想要确切的答案!这是我第一次上c++课。我是带着对VBA、MySql、CSS和HTML的先验知识来上这门课的。

我们被要求编写一个包含几个不同函数的程序。其中一个需要接收 "MM/DD/YYYY" 格式的日期输入。虽然这本身很容易;作为初学者,我只需要输入

cin >> month >> day >> year;

并在返回给用户时插入"/"。

然而,我相信我们的教授希望用户准确地输入日期"12/5/2013",或任何其他日期。


按照他的指示:

'/'可以通过cin读取。因此,阅读'/'字符并忽略它。将日设置为第三个输入,将月设置为第一个输入,将年设置为第五个输入。丢弃第二个和第四个输入

^这就是我偏离航向的地方。


到目前为止,我们只在用户每次输入后点击enter时体验到cin。所以我不知道他是否希望用户在"12"之后按回车键,然后在"/"之后,然后在"5"之后,在"/"之后,最后在"2013"之后(使用之前的例子12/5/2013表示2013年12月5日)。

有没有更有经验的人能告诉我应该怎么做?我们只被教导如何使用"cin"来接收输入(所以我们不知道其他方法来接收输入),我不知道如何去"忽略一个字符",当输入一个字符串,如'12/5/2013'确切。

我将非常感谢任何帮助!

编辑:我已经在这里寻找了答案,但是我遇到的所有答案都超出了我们所教的范围,因此不允许在作业中出现。虽然我可以很容易地理解更高级编码的逻辑,但我对自己缺乏轻松解决这些简单问题的能力感到沮丧。因此我在这里发帖。我花了几个小时浏览我们的教科书,寻找可能的答案或"忽略"输入字符串中的字符的线索,但没有找到。

这其实很简单!问题是:你可以输入不止一个东西。这意味着,如果您写入int d; std::cin >> d;,则完全可以输入30/06/2014d的值变成了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;

最新更新