Hi guys!

I want the user to enter the day, month and year in a dd/mm/yyyy format.
But what i've written doesn't seem to work.

Code:

char d[2];
char m[2];
char y[4];

cout << "Day:";
gets(d);
cout << "Month:";
gets(m);
cout << "Year:";
gets(y);

In the output, it doesn't stop for Day, Goes for month.. and suddenly program crashes at Year. Any Help?

Dani AI

Generated

As hinted, the crash is almost certainly from writing past the ends of those small C arrays and from using gets(). A string like "31" needs 3 bytes (two digits plus the '\0'), and "2010" needs 5. gets() ignores buffer size, so with char d[2] you invoke undefined behavior and crash. The safe, idiomatic C++ solutions are to read into proper types (ints) or into std::string and parse/validate.

A robust pattern: read the whole line, parse the three numbers and the separators, then validate ranges. This avoids buffer overflows and gives clear error handling.

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string line;
    std::cout << "Enter date (dd/mm/yyyy): ";
    if (!std::getline(std::cin, line)) return 0;

    std::istringstream ss(line);
    int d, m, y; char c1, c2;
    if (!(ss >> d >> c1 >> m >> c2 >> y) || c1 != '/' || c2 != '/' || !ss.eof()) {
        std::cerr << "Bad format. Use dd/mm/yyyy\n";
        return 1;
    }

    // validation follows (see function below)
}

Use a small validator that checks month range, day range (with February/leap-year rules), and a sensible year range. Example validator:

bool isLeap(int y) {
    return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}

bool validDate(int d, int m, int y) {
    if (y < 1 || m < 1 || m > 12) return false;
    int mdays[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    if (m == 2 && isLeap(y)) mdays[2] = 29;
    return d >= 1 && d <= mdays[m];
}

Troubleshooting tips: avoid gets() (use std::getline or fgets in C), prefer std::string/std::istringstream or plain int extraction with checks, compile with warnings on (-Wall) and use AddressSanitizer (-fsanitize=address) or Valgrind to catch overruns. If you mix operator>> and std::getline, clear the leftover newline with std::cin.ignore() before reading a line.

Recommended Answers

All 2 Replies

why are you using character arrays instead of integers?

why are you using C's gets() function instead of c++ cin?

If you really really want to use character arrays then you need to make them larger -- you have to account for the string's NULL terminating character. With integers you don't have to worry about that.

Thanks... I've understood...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.