Note that this code works just fine when name is a regular string instead of a c-string.
I made this test program to figure out what was causing problems with my project. Turns out that the code for name that I put works just fine, but it messes up when I add the coding that follows which asks if you want to hear the rules... This is the code:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<cstdlib>
#include<ctime>
#include<cctype>
using namespace std;
void show_name(string name)
{
cout << name << endl;
cout << "done..." << endl;
}
void show_rules()
{
}
int main()
{
char name[4];
cout << "\nPlease enter your initials (No more than 3): ";
cin.getline( name, 4 );
for( int up = 0; up < 4; up++ )
name[up] = toupper(name[up]);
while( strlen( name ) > 3 || strlen( name ) < 1 )
{
if( strlen( name ) > 3 )
cout << "Please enter no more than 3 initials!" << endl;
else if( strlen( name ) < 1 )
cout << "Please enter at least 1 initial!" << endl;
cout << "Please enter your initials: ";
cin.getline( name, 4 );
for( int up = 0; up < 4; up++ )
name[up] = toupper(name[up]);
}
char rules;
cout << "Would you like to hear the rules? (Y/N)" << endl;
cin >> rules;
rules = toupper(rules);
while( rules != 'N' && rules != 'Y' )
{
cout << "Please enter Y for Yes, or N for No!"
<< endl;
cout << "Would you like to hear the rules? (Y/N)" << endl;
cin >> rules;
rules = toupper(rules);
}
if( rules == 'Y' )
show_rules();
show_name( name );
return 0;
}
There is extra stuff there because this is a snippet of a program I'm working for a class, the main interest is in the function main(). Without the "char rules;" line and on, when it moves on to the function show_name, the name displays correctly. When the lines "char rules;" and on are added, after entering a three digit, only three digit, 2 and 1 work fine, it goes into an infinite loop saying:
Please enter Y for Yes, or N for No!
Would you like to hear the rules? (Y/N)
Please enter Y for Yes, or N for No!
Would you like to hear the rules? (Y/N)
Please enter Y for Yes, or N for No!
Would you like to hear the rules? (Y/N)
Please enter Y for Yes, or N for No!
Would you like to hear the rules? (Y/N)
Please enter Y for Yes, or N for No!
Would you like to hear the rules? (Y/N)
Please enter Y for Yes, or N for No!
Would you like to hear the rules? (Y/N)
Please enter Y for Yes, or N for No!
Would you like to hear the rules? (Y/N)
can anyone please help me figure this out?