Verifying correct input

I'm creating a program that requires the input to contain a certain parameter, that being 3 digits followed by a hyphen, and then two more digits. I cannot find any info on how to do this in my book or on the internet, and i would appreciate it if someone could show me how to, thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  // Chapter 13 Example 28.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string str = "";

	
	cout << "Enter a string in the format of 3 digits, a hyphen, and two digits: " << endl;
	cin >> str;

	while (str != "-1")

    return 0;
}

Try this

http://www.cplusplus.com/reference/cctype/isdigit/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

bool is_correct_format(const std::string& str)
{
    if (str.length() != 6)
        return false;
        
    // str =   012-45
    // index = 012345
        
    for (int i = 0; i < 3; i++)
        if (!isdigit(str[i]))
            return false;

    for (int i = 4; i < 6; i++)
        if (!isdigit(str[i]))
            return false;
    
    return str[3] == '-';
}

int main()
{
	string str;

	cout << "Enter a string in the format of 3 digits, a hyphen, and two digits: " << endl;
	cin >> str;

	if (is_correct_format(str))
	{
	    cout << "Correct format." << endl;
	}
	else
	{
	    cout << "Wrong format." << endl;   
	}

    return 0;
}
Last edited on
Thanks! Works perfectly.
Topic archived. No new replies allowed.