Thread: ifstream error message

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    45

    ifstream error message

    I am attempting to read a filename from the user and then open the file, however,
    if I press enter instead of typing a filename I get an error from the compiler:

    #######################
    Debug Assertion Failed!
    ...
    Expression: *file != _T('\0')
    ...
    #######################

    It works unless the user presses enter without typing a filename, here is the code:

    string filename;
    getline (cin, filename);
    ifstream fin(filename.c_str());


    Visual C++.NET
    Windows XP


    THANKS!

  2. #2
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    One possible solution is to make sure string filename contains the filename and is not empty.

    Kuphryn

  3. #3
    Registered User
    Join Date
    Aug 2004
    Posts
    45
    How can i test whether the string is empty or not.

    Also...if i put my 'ifstream fin(filename.c_str());' inside an 'if' statement, all other references to 'fin' generate errors because it is an undeclared identifier

    Thanks,

    quizkiwi

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >How can i test whether the string is empty or not.
    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
      std::string filename;
    
      std::getline ( std::cin, filename );
      
      if ( !filename.empty() )
        std::cout<< filename <<std::endl;
      else
        std::cerr<<"You must enter a filename"<<std::endl;
    }
    >if i put my 'ifstream fin(filename.c_str());' inside an 'if' statement, all other references to 'fin' generate errors
    So don't do that.
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Aug 2004
    Posts
    45
    Thanks, that works good!

    ->"Crushing dreams at the speed of sarcasm." ....my kinda person!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple ifstream Question
    By Paul22000 in forum C++ Programming
    Replies: 8
    Last Post: 12-05-2008, 05:34 PM
  2. how to pass an ifstream object to a function
    By chintugavali in forum C++ Programming
    Replies: 14
    Last Post: 12-18-2007, 09:58 PM
  3. ifstream
    By Wraithan in forum Tech Board
    Replies: 3
    Last Post: 09-24-2006, 01:26 AM
  4. ofstream and ifstream for searching and writing
    By johnnyd in forum C++ Programming
    Replies: 6
    Last Post: 03-17-2003, 08:34 AM
  5. Ifstream Problems
    By IlUomo in forum Windows Programming
    Replies: 1
    Last Post: 04-24-2002, 12:51 PM