Hello,

I'm new here but I need a little help please. I've gotten this program to mostly work correctly except for what seems like one small detail. My program is supposed to ask the user to enter a file name, open it and display its contents 24 lines at a time. It should wait for the user to strike a key before showing the next 24 lines. It does all of that except after the first 24 lines, it says what I want it to say which is "Press any key to continue" but it doesn't wait for the user to press any key. Instead, it waits for the user after the NEXT 24 lines and every 24 lines after that. I will paste my code here. Can anyone tell me what I might be overlooking? Thank you!

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

int main()
{
	const int SIZE = 51;
	char fileName[SIZE];
	char line[80];
	ifstream file;
	
	cout << "Enter a file name: ";
	cin >> fileName;
	file.open(fileName, ios::in);
	
	for(int i=1; !file.eof(); i++)
	{
		file.getline(line, 80);
		cout << i <<": " << line << endl;

		if (i % 24 == 0) 
		{
			cout << "Press any key to continue." << endl;
			getchar();
		}
		
		
	}
	
	file.close();
	return 0;
}

Dani AI

Generated

The root cause is the leftover input in stdin after reading the file name with operator>> and the mixing of C and C++ input functions. was on the right track: the newline left by cin >> fileName will be consumed by the first pause call unless you clear it immediately. A more robust pattern is to (a) read the filename with std::getline so nothing is left in the input buffer, (b) check the file opened successfully, and (c) read the file with std::getline(file, line) in a loop (avoid !file.eof()).

A concise, safe example that avoids the buffering/grabbing problems shown in earlier posts:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::string fileName;
    std::cout << "Enter a file name: ";
    std::getline(std::cin, fileName);            // no leftover newline

    std::ifstream file(fileName);
    if (!file) { std::cerr << "Cannot open file\n"; return 1; }

    std::string line;
    int count = 0;
    while (std::getline(file, line)) {
        std::cout << ++count << ": " << line << '\n';
        if (count % 24 == 0) {
            std::cout << "Press Enter to continue...";
            std::cin.get();                        // waits for a single Enter
        }
    }
    return 0;
}

If you must keep cin >> fileName, add this immediately after it:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); — that clears the trailing newline so the first pause actually waits. The “press Enter twice” symptom comes from leaving both an ignore/consumption call and then also calling a pause function; only clear the buffer once and use one pause method. Also avoid mixing getchar() (C) with std::cin (C++) — use std::cin.get() or, if you need a true “press any key without Enter,” use a platform-specific call (Windows _getch() / <conio.h>, or termios on POSIX). Finally, as emphasized, post future snippets with code tags so responders can see line numbers and formatting.

Recommended Answers

All 6 Replies

Put in a cin.ignore(); right before your getchar() call. There is probably something left over in the input stream after your getline call (though I think getline should discard the newline but maybe I'm thinking of something else) which is taken in by your getchar ending the first pause.

Another thing to watch out for is your use of !file.eof. Take a look at this thread for an explanation.

Put in a cin.ignore(); right before your getchar() call. There is probably something left over in the input stream after your getline call (though I think getline should discard the newline but maybe I'm thinking of something else) which is taken in by your getchar ending the first pause.

Another thing to watch out for is your use of !file.eof. Take a look at this thread for an explanation.

Hey! Thanks! That solved that problem but now when I run the program, after the first group of 24 lines, I have to hit enter twice to continue. I DO think it's better than what it was doing before. Maybe I'm just being a perfectionist but now I'm wondering why after the first group of 24 lines, I have to hit enter twice to continue. Any thoughts? Even if not, thanks a bunch for the help you already gave!

I'm embarrassed because I thought I had tested it. It turns out that it's trickling down from the cin >> fileName call. Put the cin.ignore() immediately after that line (13 I think*) and take the other one out. I wish I'd seen it before.

*also please use the code tags on your post (that would give the line numbers and keep the formatting):

[code]

//code goes here

[/code]

I'm embarrassed because I thought I had tested it. It turns out that it's trickling down from the cin >> fileName call. Put the cin.ignore() immediately after that line (13 I think*) and take the other one out. I wish I'd seen it before.

*also please use the code tags on your post (that would give the line numbers and keep the formatting):

[code]

//code goes here

[/code]

Please forgive me...I'm still new posting anything in these forums but...code tags? I'm sorry. That probably seems stupid of me to not know what that means. Like I said, I'm new to posting in these forums and as far as programming goes, I'm still pretty new to that too. I'm only in my second computer science class right now. Thanks.

I'm embarrassed because I thought I had tested it. It turns out that it's trickling down from the cin >> fileName call. Put the cin.ignore() immediately after that line (13 I think*) and take the other one out. I wish I'd seen it before.

*also please use the code tags on your post (that would give the line numbers and keep the formatting):

[code]

//code goes here

[/code]

Thank you sooooo, SOOOOOO MUCH!!!!!!!! That last bit of advice worked like a charm!!! (It was, in fact, immediately after line 13 btw. Thanks for being so specific. It saved me some time.) Now it seems to do EXACTLY what I need it to do! However, I just now realized that I need to include something that will basically catch an invalid file input from the user. I think I can find something like that in the book I have though. If it gives me problems, I guess I'll just be making another post. LOL Thank you SO much again!

Please forgive me...I'm still new posting anything in these forums but...code tags? I'm sorry. That probably seems stupid of me to not know what that means. Like I said, I'm new to posting in these forums and as far as programming goes, I'm still pretty new to that too. I'm only in my second computer science class right now. Thanks.

CODE TAGS
read any of the requested information posted all over this site about CODE tags, like
1) in the Rules you were asked to read when you registered
2) in the text at the top of this forum
3) in the announcement at the top of this forum titled Please use BB Code and Inlinecode tags
4) in the sticky post above titled Read Me: Read This Before Posting
5) any place CODE tags were used, even in responses to your posts
6) Even on the background of the box you actually typed your message in!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.