Home > Net >  How to do press any key to continue prompt?
How to do press any key to continue prompt?

Time:11-22

I am writing a program where the code reads off the text from a .txt file in where anything more than 24 lines must be continued with the enter key, but unsure how to put in the prompt asking for the enter key that doesn't mess up the formatting as it must show the first 24 lines instantly.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
....    

{
    cout << "Please enter the name of the file: ";
    string fileName;
    getline(cin, fileName);

    ifstream file(fileName.c_str(), ios::in);

    string input;
    ifstream fin(fileName);
    int count = 0;

    while (getline(fin, input))
    {
        cout << count << ". " << input << '\n' ;
        count  ;
        if (count % 25 == 0)
            cin.get();
    }
    cin.get();
    system("read");
    return 0;
}

The part of the code that does the function and if I insert the prompt into here

if (count % 25 == 0)
cout << "Press ENTER to continue...";
cin.get(); 

it just has it where you must press enter for each line. Putting the prompt anywhere just messes it up in other ways.

CodePudding user response:

Just place braces {} for the appropriate if (as pointed out in the comments) and your program will work.

Note also that there is no need to use ifstream twice as you did in your program.

#include <fstream>
#include <string>
#include <iostream>
   
int main()
{

    std::string fileName;
    std::cout<<"Enter filename"<<std::endl;
    std::getline(std::cin, fileName);
    
    std::ifstream file(fileName);

    std::string line;
    int count = 1;
    if(file)
    {
        while (std::getline(file, line))
        {
            std::cout << count << ". " << line << '\n' ;
            
            if (count % 25 == 0)
            {
               std::cout<<"Press enter to continue"<<std::endl;
                std::cin.get();
            }
            count  ;
        }
    }
    else 
    {
        std::cout<<"file cannot be opened"<<std::endl;
    }
      
    return 0;
}
  • Related