HELP D: ifstream

closed account (ivDwAqkS)
well, I did a program that reads as many lines of the file you specify. the program is 99% perfect but this little bug is stressing me.

if you would like to see the bug you could test it , creating a txt file on your desktop and write 10 lines and test it. it double write a message and I don't want it to double write it D:, here is the code and I specified the line wich double print.

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;

#define COL_WIDTH 80

int get_number();
int main(){
    int c;
    int i;

    char filename[MAX_PATH + 1];
    char input_line[COL_WIDTH + 1];

    cout << "Enter a file name and press ENTER: ";
    cin.getline(filename, MAX_PATH);
    strcat(filename, ".txt");
    ifstream file_in(filename);

    if(!file_in){
        cout << filename << " could not be opened"<< endl;
        return -1;
    }
    cout << "Please enter the numbers of lines\nyou wanna read: ";
    //already corrected added cin.ignore();
    cin >> c;
    cin.ignore();
    while(true){
        for(i = 1; i <=c && !file_in.eof(); i++){
            file_in.getline(input_line, COL_WIDTH);
            cout << input_line << endl;
        }
        if(file_in.eof())
            break;
        //this cout is double printing I don't know why help
        cout << "More? Press HOW MANY LINES to display ?\nor press Q to quit)";
        c = get_number();
        if(c=='Q' || c=='q' || c==0)
            break;
    }
    return 0;
}

int get_number(){
    char number[100];
    cin.getline(number, 100);
   //I know this is not necessary but its an additional feature
    if(strcmp(number, "one")==0)
        return 1;
    if(strcmp(number, "two")==0)
        return 2;
    if(strcmp(number, "three")==0)
        return 3;
    if(strcmp(number, "four")==0)
        return 4;
    if(strcmp(number, "five")==0)
        return 5;
    return atoi(number);
}
Last edited on
closed account (ivDwAqkS)
does anybody know why does it double print it?
On line 27, you have cin >> c. This leaves a newline character in the stream which is picked up by the call to getline on line 46. The program considers this input, so it runs another loop, which is why your line is printed twice.
You can simply discard that extra newline with either cin.ignore() (more flexible) or cin.get() (only one character).

Also, why confuse the user by saying "press ENTER to quit", when you quit only if the user enters 'Q' or 'q'? (This will also cause trouble if the user enters the ASCII equivalents.)
closed account (ivDwAqkS)
LOL yes I am sorry I need to correct that XD about the ENTER and thanks.
Topic archived. No new replies allowed.