Validation Loop Help

Hello, I'm not looking for you to write the code for me, I'm just looking to be pointed in the right direction. If you could provide a template or give some tips, that would be amazing. The question is as follows..

Write a validation loop that prompts the user for a string with less than five characters. If the string is longer than four characters, print a message including the string and prompt the user again. Declare string variable str to hold the value.

Thank you!:)
Last edited on
Start loop that will run until you break out of it:
http://www.cplusplus.com/doc/tutorial/control/

Get user input:
http://www.cplusplus.com/doc/tutorial/basic_io/

Get length of string using suitable function:
http://www.cplusplus.com/reference/string/string/

If length is suitable, break out of loop.

This is what I have so far...
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 <conio.h> // For function getch()
#include <cstdlib> // For several general-purpose functions
#include <fstream> // For file handling
#include <iomanip> // For formatted output
#include <iostream> // For cin, cout, and system
#include <string> // For string data type
using namespace std; // So "std::cout" may be abbreviated to "cout"

int main()
{
	std::string str;

	cout << "Enter a string with less than 5 characters: ";
	cin >> str;

	while (str > 5)
		cout << "Invalid Input. Try Again." << endl;
		cout << "Enter a string with less than 5 characters: ";
		cin >> str;
	

	cout << "Your Input Is Valid." << endl;

	return 0;
}

while (str > 5)

You need the string function that gets the string length for this comparison to the value 5, not just the name of the string. The string functions are at the link Repeater posted above.

The lines that are the repeating code of the while loop need to be wrapped in { } braces.

Also - is the string allowed to be exactly 5 characters? The text message says less than 5, but the check in the while loop would allow less than or equal to 5.
At risk of repeating wildblue, in C++, indentation carries no meaning.

This:

1
2
3
4
	while (str > 5)
		cout << "Invalid Input. Try Again." << endl;
		cout << "Enter a string with less than 5 characters: ";
		cin >> str;


is identical to:

1
2
3
4
	while (str > 5)
cout << "Invalid Input. Try Again." << endl;
cout << "Enter a string with less than 5 characters: ";
		                                                       cin >> str;


and both of them are identical to:

1
2
3
4
5
6
while (str > 5)
{
    cout << "Invalid Input. Try Again." << endl;
}
cout << "Enter a string with less than 5 characters: ";
cin >> str;


Use the braces.

Last edited on
Topic archived. No new replies allowed.