for loop help

I am trying to let the user redefine variable int yn; to be able to stop the loop when the user inputs a value other than 'y'. It doesn't want to let me do that and it repeatedly prints out the loop without pausing for the cin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cstdlib>
#include <iostream>
#include <sstream>

using namespace std;
char getname(char[]);
int getamount(int);
int main(int argc, char *argv[])
{   int element[40];
    int yn='y';
    for (int n=1; yn=='y'; n++)
    {cout << "Enter the names of the elements you will be using";
    cin >> element[n];
    cout << "Any more elements?(y/n)";
    cin >> yn;
}

    
    system("PAUSE");
    return EXIT_SUCCESS;
}
You'll want to declare yn as a char value instead:
char yn='y';
This is a little example that
could be helpful


Eyenrique-MacBook-Pro:Desktop Eyenrique$ ./stopLoop 
Enter the names of the elements you will be using
Name #1: Enderman

Any more elements? (y/n): y
Name #2: Skull

Any more elements? (y/n): y
Name #3: Zombie

Bye.!!!!



Eyenrique-MacBook-Pro:Desktop Eyenrique$ ./stopLoop 
Enter the names of the elements you will be using
Name #1: Spider

Any more elements? (y/n): y
Name #2: Bow

Any more elements? (y/n): n

Bye.!!!!


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
//stopLoop.cpp
//##

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <string>
using std::string;
using std::getline;


int main(){
        const int SIZE=3; //you can use any size 40,3,7..,etc.
        string names[SIZE];
        char option;

        cout<<"Enter the names of the elements you will be using"<<endl;

        for(int i=0;i<SIZE;i++){
                
                cout<<"Name #"<<i+1<<": ";
                getline(cin,names[i]);

                if(i+1!=SIZE){ //if is not the last element then ask for more elements.
                cout<<"\nAny more elements? (y/n): ";
                cin>>option;
                cin.ignore();

                if(!(option=='y'||option=='Y'))break;
                }//end if

        }//end for

        cout<<"\nBye.!!!!"<<endl;

return 0; //indicates success
}//end of main 
As long double main points out, you should define yn as char instead of int.

Also in your for loop, you start your index from 1. This means that in your array element, the first element is undefined. This should be avoided.
Topic archived. No new replies allowed.