Ifstream in Dev-C++

I've been having some trouble with ifstream in Dev-C++. Here's my code:

[code]#include
#include
#include

using namespace std;

int main(int argc, char *argv[])
{
ifstream myFile;
char* myText;
system("PAUSE");
myFile.open("Hello.txt",ios::in);
if (!myFile.is_open())
return EXIT_FAILURE;
system("PAUSE");
while (myFile.eof()) {
myFile >> myText;
cout << myText;
}
system("PAUSE");
return EXIT_SUCCESS;
}[/code]

It it opens the file, no problem, but when it gets to the loop, it doesn't print anything, just goes to the next PAUSE. What am I doing wrong?

Best Regards,
CodeKing

Comments

  • : I've been having some trouble with ifstream in Dev-C++. Here's my
    : code:
    :
    : [code]: #include
    : #include
    : #include
    :
    : using namespace std;
    :
    : int main(int argc, char *argv[])
    : {
    : ifstream myFile;
    : char* myText;
    : system("PAUSE");
    : myFile.open("Hello.txt",ios::in);
    : if (!myFile.is_open())
    : return EXIT_FAILURE;
    : system("PAUSE");
    : while (myFile.eof()) {
    : myFile >> myText;
    : cout << myText;
    : }
    : system("PAUSE");
    : return EXIT_SUCCESS;
    : }[/code]:
    :
    : It it opens the file, no problem, but when it gets to the loop, it
    : doesn't print anything, just goes to the next PAUSE. What am I
    : doing wrong?
    :
    : Best Regards,
    : CodeKing


    Are you wanting to use ofstream for output rather then input? How about just using fstream?
  • Hi,

    1. There is no problem in using 'ifstream' and you are properly using input from the file.

    2. You are declaring a 'char *' variable (myText), but not initialized to store a string.

    3. Your condition of while loop is : 'myFile.eof()', but it means that do the while until it is in the end of the file, but you want the opposit!

    4. Close your file handles, when you don't need them more : 'myFile.close();'

    -> The correct (tested) code :

    [code]#include
    #include
    #include

    using namespace std;

    int main(int argc, char *argv[])
    {
    ifstream myFile;
    char* myText = [color=Blue]new char[30][/color]; // the buffer size depends on your strings sizes

    system("PAUSE");

    myFile.open("Hello.txt",ios::in);

    if (!myFile.is_open())
    return EXIT_FAILURE;

    system("PAUSE");

    while ([color=Blue]!myFile.eof()[/color]) {
    myFile >> myText;
    cout << myText;
    }

    [color=Blue]myFile.close();[/color]

    system("PAUSE");
    return EXIT_SUCCESS;
    }[/code]
    --------------------------------------
    - I don't have Time To waste The Time!
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories