Problem with Inputting File Name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
                char filename[200];
                int i=0;
                int j;
                char Read[1000];
                ifstream file;
                do{
                    cout << "Please give file name: ";
                    cin.getline(filename, sizeof(filename));
                    file.open(filename);
                }while(!file.fail());
                bool done=false;
                do{
                    file >> j;
                    if(file.eof()){
                         done=true;
                    }
                    else{
                        Read[i]=j;
                        i++;
                    }
                }while(!done);

The idea of this code is to read the information in a file, which will consist of a string of random letters, and save it to an array so I can use at information later.
But, for some reason, when compiled, this code does not let the user type anything when prompted. That is, it gets to the "Please give file name: " line, and completely locks up.
What am I doing wrong here?
Last edited on
I'm going to bump this.
Assistance with this issue would be very much appreciated. I am completely stuck and I can't seem to find any relevant tutorials.
1
2
3
4
int j;
char Read[1000];
file >> j;
Read[i]=j;
j is an integer, you will fail if you try to read a letter with an integer. file gets in a state of error and never reach file.eof()
Read your file like this while( file >> var ){

Also cin.getline(filename, sizeof(filename)-1); Don't forget that it must end with '\0'
Well, I did most of what you said.
The result looks like this, and, unfortunately, still locks up at the same moment.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    ifstream file;
    char filename[200];
    int x=0;
    char y;
    cout << "Please give file name: ";
    cin.getline(filename, sizeof(filename)-1);
    do{
        file.open(filename);
    }while(!file.fail());
    bool done=false;
    do{
        while(file >> y){
        if(file.eof()){
            done=true;
        }
        else{
            Read[x]=y;
            x++;
        }
        }
    }while(!done);

This is an improvement from where I got myself after a bit of experimenting. I locked this entire file processing bit into a function on its own that the program can call on later, and, up until implementing your fix, the program completely crashed when I tried to use this part.
The array Read[] is a global variable, not initialized in this function.
Last edited on
Don't check for eof. while(file >> y) is already doing that (when it reaches eof, the condition will be false)
while( file>>Read[x] ) x++; That's all you need.
Last edited on
Topic archived. No new replies allowed.