Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do press any key to continue prompt?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading