Search code examples
c++loopsresumepause

How do I print an array, pause it and continue to print the array in c++?


How do I display 3 names at a time, pausing to let the user press a key before the list continues displaying.

My code now only loops the first 3 values of the array

#include <iostream> 
#include <string> 
#include <iomanip> 

using std::setw; 
using namespace std; 

int main() { 

    string a; 
    string names[10]; //size of array 

    for (int i = 0; i < 10; i++) 
    { 
        std::cout << "Enter name "; 
        std::cin >> a; //user input 

        names[i] = a; //assigns input to array 
    } 
    cout << "\n"; 

    for (int k = 0; k < 10; k++) 
    { 
        for (int j = 0; j < 3; j++) 
        { 
            cout << names[j] << endl; 
        } 

        system("pause"); 
    } 

}

Solution

  • I changed the answer based on your comment. Instead of sleeping we just pause and wait until user inputs anything into the keyboard. Also a note, since you're using namespace, you don't need to include std::, I decided to use it since I was unsure what way you wanted.

    #include <iostream>
    #include <string>
    #include <iomanip>
    
    using std::setw;
    using namespace std;
    
    int main() {
    
        string a;
        int pauseCheck = 0; //new var
        string names[10]; //size of array
    
        for (int i = 0; i < 10; i++) {
            std::cout << "Enter name ";
            std::cin >> a; //user input
    
            names[i] = a; //assigns input to array
        }
        cout << "\n";
    
        for (int k = 0; k < 10; k++) {
    
            cout << names[k] << endl;
            pauseCheck++; //increments check
    
            if (pauseCheck == 3) { //if equals 3
                system("pause"); //we pause till user input
                pauseCheck = 0; //reset pause check
            }
        }
        system("pause"); //last and final pause before program ends
    }