Detecting number of input characters?

I have a program which intakes an hour input and minute input,
I want to figure out how to limit the hour input to one digit, and limit the minutes input to two digits.
As well, for the minutes input I would like to be able to detect when there is only one input character so I can add a "0" to the time output.
So it wouldn't output 9:1, rather than 9:01

I want to incorporate the current while statement I have that eliminates any possible non-numeric input.

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
43
44
45
46
47
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void func(int, int);

int main()
{
	int hour =0;
	bool in1 = false;

	while (!in1)
	{
		cout << "Enter hour: ";
		string line;
		getline(cin, line);
        istringstream is(line);
        char dummy = '\0';
        if (!(is >> hour) || (is >> ws && is.get(dummy)))
			cout << "Invalid input. Try again!\n";
        else
            in1 = true ;
    }
bool in2 = false;
int min =0;
	while (!in2)
	{
		cout << "Enter minutes: ";
		string line;
		getline(cin, line);
        istringstream is(line);
        char dummy = '\0';
        if (!(is >> min) || (is >> ws && is.get(dummy)))
			cout << "Invalid input. Try again!\n";
        else
            in2 = true ;
    }

	func(hour, min);

    return 0;
}
void func(int h, int m)
{
cout << "The time is " << h << ":" << m << endl;
}
I want to figure out how to limit the hour input to one digit, and limit the minutes input to two digits.

I would just make sure that (hour <= 9) and (min <= 59).

for the minutes input I would like to be able to detect when there is only one input character

Just check whether this holds or not -> (min <= 9).
okay I obviously used a bad example because all problems are more logically overcome with < and >, though I am literally wanting to know how to determine if an input has a certain number of characters in it, and how to limit the number of input characters.
a way that would be able to work with alphabetical characters as well.
In that case you can just use the string::length or string::size member functions.

http://www.cplusplus.com/reference/string/string/length/
http://www.cplusplus.com/reference/string/string/size/
thankyou that helps. Now I can capture the number of characters and limit possibilities to certain numbers of characters.
However, I still need to know how to input a character in the beginning of a string.
For example, if 1 is entered for minuted, I would be able to identify if a string size = 1, the variable would require a "0" inserted to the beginning
In another example, if I identify that someone enters say 3 characters, I would want to add either a 0 or whatever to the beginning of that string.
~ for whatever reason.

I still need to know how to input a character in the beginning of a string.

You can use the + operator for this. Example:

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
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    istringstream input(
        "5\n"
        "34\n"
        "0\n"
        "12\n"
        "7\n");

    string digits;

    while (getline(input, digits)) {

        if (digits.size() < 2)
            digits = "0" + digits;

        cout << digits << endl;
    }
}
I seem to be getting this error I try an if statement where (minutes = "60")
minutes being a string


error C2451: conditional expression of type 'std::basic_string<_Elem,_Traits,_Ax>' is illegal
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>,
1>            _Ax=std::allocator<char>
1>        ]
1>        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

its everytime i set a string equal to some characters in an if statement, how do I get around this?
Post the whole code.
Not sure without seeing your code, but make sure you are doing the following:

if(strcmp(minutes,"60"))

and not

if(minutes = "60") WRONG

The first is a logical comparison, the second is an assignment. Also, it's good practice if you are going to use a constant value like 60 for minutes to create a const variable or global definition and set it, that way if you need to make adjustments to this value later, you only have to change it in one place. Good luck and please post your full code if you continue to have issues.
make sure you are doing the following:

if(strcmp(minutes,"60"))

This is wrong, regardless of how minutes is defined. In order to get this to compile, the type of minutes has to be (something implicitly convertible to) const char * (looking at the original code makes me think this is unlikely). But even if minutes has an appropriate type, this is not how strcmp works.
Last edited on
Here is the most recently revised code

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

//void func(int, int);

int main()
{
	int hour =0;
	bool in1 = false;
	string minutes;

	while (!in1)
	{
		cout << "Enter hour: ";
		string line;
		getline(cin, line);
        istringstream is(line);
        char dummy = '\0';
        if (!(is >> hour) || (is >> ws && is.get(dummy)) || (hour >12))
			cout << "Invalid input. Try again!\n";
        else
            in1 = true ;
    }

bool in2 = false;
int minss =0;
	while (!in2)
	{
		cout << "Enter minutes: ";
		string line2;
		getline(cin, line2);
        istringstream is(line2);
        char dummy = '\0';
        if (!(is >> minss) || (is >> ws && is.get(dummy)) || (minss >60))
		{
					cout << "Invalid input. Try again!\n";
		}
        else
		{
			if (minss ==60 && hour ==12)
			{
				minss = 0;
				hour = 1;
				in2 = true;
			}
			else 
			{
				stringstream convert;
				convert << minss;
				minutes = convert.str();
				if (minutes = 60)
				{

				hour = hour + 1;
				minutes = "00";
				in2 = true;
				}
				else
				{
					ostringstream convert;
					convert << minss;
					minutes = convert.str();
					if (minutes.size() < 2)
					{
						minutes = "0" + minutes;
						in2 = true;
					}
					else 
					in2 = true ;
				}
			}
		}
    }
cout << "The time is " << hour << ":" << minutes << endl;
	//func(hour, min);

    return 0;
}
/*void func(int h, int m)
{
cout << "The time is " << h << ":" << m << endl;
}*/ 


If you omit lines 50-52 and change line 53 to if (minss ==60) and line 57 to minss = 0; it completely works except when "60" is entered for the minutes input, the output turns out to be nothing...

lines 62-64 i added to convert the int type "minss" to string "minutes"

@m4ster r0shi I may be missing how to fully implement the code you provided with mine and still adding the wrong input check, sorry.
Last edited on
Here is my revised code
I identified string minutes outside the while statement for the input
and set the end output to display the string "minutes"
all only because it requires the double 0 "00" safety if "60" is the input (as hours is + 1)
though the only problem now, is that of course since the minutes is a string, if zeroes are added before the actual number when being inputted, the zeroes will also be outputted.
unlike hours, which is always an integer, it can not display zeroes before a number on the output.
I tried adding to the end stoi but for some reason it's giving me an error saying stoi is unidentified..?
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
	int hour =0;
	bool in1 = false;

	while (!in1)
	{
		cout << "Enter hour: ";
		string line;
		getline(cin, line);
        istringstream is(line);
        char dummy = '\0';
        if (!(is >> hour) || (is >> ws && is.get(dummy)) || (hour >12))
			cout << "Invalid input. Try again!\n";
        else
            in1 = true ;
    }

bool in2 = false;
int minss =0;
string minutes;
	while (!in2)
	{
		cout << "Enter minutes: ";

		getline(cin, minutes);
        istringstream is(minutes);
        char dummy = '\0';
        if (!(is >> minss) || (is >> ws && is.get(dummy)) || (minss >60))
		{
					cout << "Invalid input. Try again!\n";
		}
        else
		{
			if (minss ==60 && hour ==12)
			{
				minutes = "00";
				hour = 1;
				in2 = true;
			}
			else 
			{
				if (minss ==60)
				{

				hour = hour + 1;
				minutes = "00";
				in2 = true;
				}
				else
				{

					if (minutes.size() < 2)
					{
						minutes = "0" + minutes;
						in2 = true;
					}
					else 
					in2 = true ;
				}
			}
		}
    }
//int mins2 = stoi (minutes);
cout << "The time is " << hour << ":" << minutes << endl;
//cout << "The time is " << hour << ":" << mins2 << endl;

    return main();
}



EDIT: please excuse return main(); I use it for quick testing purposes only of course
Last edited on
though the only problem now, is that of course since the minutes is a string, if zeroes are
added before the actual number when being inputted, the zeroes will also be outputted

Add a check like this -> if (minutes.size() > 2) { /* ... */ }
next to your existing -> if (minutes.size() < 2) { /* ... */ }.

Inside the body of the new if statement, set minutes to be
the substring of itself that contains its last two characters.

Useful link -> http://www.cplusplus.com/reference/string/string/substr/

EDIT:

Another problem you have now, though, is that minutes might also contain trailing spaces. Perhaps a better solution would be to just convert minss back to a string once you verify that you have a valid input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* ... */

        if (!(is >> minss) || (is >> ws && is.get(dummy)) || (minss >60))
        {
            cout << "Invalid input. Try again!\n";
        }
        else
        {
            ostringstream os;
            os << minss;
            minutes = os.str();

            /* ... */
        }

/* ... */
Last edited on
interestingly, I placed || (minutes.size() > 2) right on line 34 and now the one and only error is that the if (minutes.size() < 2) on line 58 now gets overlooked if there is a space before the a single digit
So then a zero won't be added, it will be 12: 1
I dont know how to retrieve the first value of a string and check if it's equal to a space.
maybe convert to char and cout.put() and ascii a space and check that but I'm even having problems converting a string to char...

If you convert minss back to a string as I do in my edit above, you won't have this problem, as any trailing and leading spaces will disappear. Actually, you don't even have to add the extra condition you mention here. But if you want to do it your way, you can access individual characters of a std::string using the [] operator (i.e. the same way you would access elements of an array).

http://www.cplusplus.com/reference/string/string/operator[]/
Last edited on
Topic archived. No new replies allowed.