### Thread: Looping with amount of letters?

1. #### Looping with amount of letters?

If I type more then one letter/number in the input the, "you must answer with a 1 or a 2" text shows up for the amount of characters/numbers typed in. For example, I type "asd" (without quotes) It will say, "you must answer with a 1 or a 2" three times! Here is my code:

#include <iostream>

int main()
{
using namespace std;

int x = 1;
char y;

do

{
cout << "Is x 1 or 2? (If you type anything else then 1 or 2 the program will repeat until a valid value is entered.\n";
cin >> y;
cout << "\n";

if(y != '1' && y != '2')
cout << "Sorry, you must answer with a \"1\" or a \"2\"!\n\n";
}

while (y != '1' && y != '2');

int int_y;
if(y == '1') int_y = 1;
else int_y = 2;

if (y == '1')
cout << "Correct! X is one\n";
else if (y == '2')
cout << "You are wrong!\n";

return 0;

}
2. No Profile Picture
Contributing User
Devshed Beginner (1000 - 1499 posts)

Join Date
Feb 2001
Posts
1,481
Rep Power
16
Hi andy,

OK, there's a little hitch in my solution. Here's what's happening: if you enter "asd", cin only reads the first character, so when the loop executes again, the "sd" is still in the input stream, so cin goes ahead and reads the next character without the user doing anything, so that's why you're getting the loop message repeated 3 times.

What you need to do is read in everything the user inputs. There is a way to do that with:

cin.getline();

That function takes two parameters(or more). The first parameter should be the name of a character array, and the second is an integer which is the maximum number of characters you want to read.

so, you can do something like this:

const int maximum=1000;

and then use:

to read in data. The function will read in all the characters the user entered before hitting return(\n signals the end of the input) up to a maximum of 1,000 characters.

Then you have to change your if-statement tests and while-loop test to check whether:

is equal to '1' or '2'. Ideally, you could use the code you have, and then clear the input stream to get rid of the extra characters, but I don't know how to do that.
Last edited by 7stud; February 10th, 2003 at 01:32 PM.
3. I don't understand what the '={0};' is for in this line:

4. No Profile Picture
Contributing User
Devshed Beginner (1000 - 1499 posts)

Join Date
Feb 2001
Posts
1,481
Rep Power
16
Hi,

Here is the way you initialize an array:

int numbers[3]={5, 10, 7};

It's good programming style to always intialize your variables to something like 0 when you declare them:

int count=0;
float number=0.0f;

If you only list some of the numbers for an array, the other indexes will automatically be initialized with 0:

int other_numbers[3]={0, 1};

If you printed out that array, you would see that:

other_numbers[0]=0;
other_numbers[1]=1;
other_numbers[2]=0;

So, if you want to intialize a whole array with 0, you only have to intialize the first value with 0, like this:

int more_numbers[100]={0};