well im writing a program where the user enters a number from 2 to 1000 and it displays the prime numbers. Its in a loop and i want it to stop when the users enters 'n' or 'N'
well when i type n or N the program goes crazy haha. help me or if you can think of a better way to stop it using N or n !!

#include<iostream.h>

void main()
{
  int num,isprime;

do
{
cout<<"Enter a number between 2 and 1000 :";
cin >> num;
  for( int i = 2 ; i <= num; i++)
  {
     isprime  = 1;
     for( int j = 2 ; j <= i ; j++)
     {
        if( i == j)
           continue;
        else if( i % j == 0)
        isprime = 0;
     }
     if(isprime)
     cout<<i<<" " << endl;
  }
}while (num != 'n' || 'N');
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

The >> operator is type safe, it knows what type you want and doesn't allow any characters that don't fit the type. What Edward means is that 'N' and 'n' aren't legitimate characters in an int. :) When you type one of those, cin goes into an error state and will refuse to read anymore characters until you clear it. There are a bunch of things you can do to fix the problem, but the best in Ed's opinion is to read everything as a string and do simple parsing:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
  while (true) {
    std::cout << "Enter a number between 2 and 1000: ";

    std::string input;

    getline(std::cin, input);
    
    // Break on n or N
    if (input[0] == 'n' || input[0] == 'N')
      break;

    std::stringstream iss(input);
    int num;

    iss >> num;

    // Prime stuff here
  }
}

This code is simplified by removing error checking. It's always better to check input functions for success instead of assuming, but for simple homework programs it's not that big of an issue. ;)

thank you Radical Edward, I was able to make it run properly with your help.

This question has already been answered. Start a new discussion instead.