function can't print line from file

Hey,

The line is not printed !!
How can I print the next line from file ??

This is the code here
Thank you


void get_input(node* head)
{

string line="";
node *list=NULL;
node *tail=NULL;
int flag=0;

ifstream myfile("file1.txt");

myfile.open("file1.txt");
if(myfile.is_open())
{
cout<< "File successfully open"<<endl;
while(!myfile.eof())
{

getline (myfile,line);
cout<<line<<endl;
list=new node;
if(flag==0)
{
head=list;
flag++;

}

list->next=NULL;
list->code=line;
tail=list->next;
list=tail;
myfile.close();
cout<<"1"<<endl;
}

myfile.close();
}
else
cout<<"Unable to open file"<<endl;

}
it prints an empty line !!!
Maybe is is indeed empty. Why not?:)
because the file is not empy !! so the line should has something
Try the following way

1
2
3
ifstream myfile;
 
myfile.open("file1.txt");
I checked while(myfile.good()) and it returns falls.
there is no problam with while(myfile.bad())... it returns 0.
so it should be the 'fail', checked while(myfile.fail()) and it returned 1 ... so that is the problem and that may help you guide me.

Thank you
Thanks vlad,

It worked for the first line but then I got an empty line and the while(file.good()) didn't pass after that !!
Show your updated code.

void get_input(node* head)
{

string line="";
node *list=NULL;
node *tail=NULL;
int flag=0;

ifstream myfile;

myfile.open("file1.txt");
if(myfile.is_open())
{
cout<< "File successfully open"<<endl;
while(myfile.good())
{

getline (myfile,line);
cout<<line<<endl;
list=new node;
if(flag==0)
{
head=list;
flag++;

}

list->next=NULL;
list->code=line;
tail=list->next;
list=tail;
myfile.close();
cout<<"1"<<endl;

cout<<head->code<<endl;
}

myfile.close();
}
else
cout<<"Unable to open file"<<endl;

return;
}
But you output only one line. Look at your loop. You are closing your file in the body of the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
while(myfile.good())
{

    getline (myfile,line);
    cout<<line<<endl;
    list=new node;
    if(flag==0)
    {
        head=list;
        flag++;
    }
 
    list->next=NULL;
    list->code=line;
    tail=list->next;
    list=tail;
    myfile.close();
    cout<<"1"<<endl;

    cout<<head->code<<endl;
}


Last edited on
opppsss... :)
Thank you Vlad !!
Topic archived. No new replies allowed.