force correct input
Oct 19, 2015 at 4:09am UTC
in my county registration number, consists of 6 charaters( numbers/letters )
trying to force correct input so will allways exit function with total of 6 characters in the string.
problem happens when it gets to while loop.
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
# include <iostream>
# include <conio.h>
using namespace std;
int main()
{
char rego[8];
int j = 0;
int c = 0;
cout << "enter rego number " ;
cin >> rego;
cout << "you said " << rego << endl;
int i = 0;
for ( i ; i < strlen( rego ); i++ )
{
//cout << i; getch();
c++;
}
cout << i; getch();
int k = 0;
if ( i != 6 )
{
cout << c <<"ERROR:" ;
while ( i != 6 || k == 6 ) )
{
cout << "enter 6 character rego " ;
cin >> rego;
for ( j ; j < strlen( rego ); j++ )
{
for ( k; k < j; k++ )
{
//cout << rego[k];getch();
}
}
//cout << j;
cout << k;getch();
}
}
cout << "passed" ;getch();
}
Oct 19, 2015 at 5:03am UTC
If i is not equal to 6, then i will never be 6 on line 28. Instant infinite loop.
In addition, you never reset the values of j or k, although you clearly should.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
int main()
{
std::string line;
std::cout << "Enter a 6 character rego:\n> " ;
while (getline(std::cin, line) && line.length() != 6)
std::cout << "ERROR: You must enter a 6 character rego.\n> " ;
std::cout << "You entered \"" << line << "\"\n" ;
}
Last edited on Oct 19, 2015 at 5:03am UTC
Oct 19, 2015 at 6:49am UTC
great thanks, i see where i went wrong now.
reset values? why should i do that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
char rego[ 8 ];
cout << "enter rego number " ;
cin >> rego;
while ( strlen( rego ) != 6 )
{
cout << "ERROR: enter 6 character rego " ;
cin >> rego;
}
}
Last edited on Oct 19, 2015 at 7:29am UTC
Oct 19, 2015 at 9:09am UTC
reset values? why should i do that?
Because the program logic required it.
Your code is error prone. Consider using a std::string or otherwise limiting the input extracted into
rego to what the buffer can actually hold.
Topic archived. No new replies allowed.