I'm making a program, and I'm at the beginning where I'm just reading the information in. The goal of this short bit of code is to read in a date (when I finish the program it should be able to read in multiple dates from a file, but I'm keeping it simple for now).

The only thing the input file has in it is a date in dd/mm/yyyy form for now. Here's the code:

-----------------------

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <cstring>


int main()
{
int month=0, month2=0, day=0, day2=0, year=0, year2=0;
ifstream infile;
infile.open("input.txt");//change fileName to w/e name you end up using
if (infile.fail("input.txt")){ cout<<"Did not open";
exit(1);
}

infile>>month;
infile.ignore(1000,'/');
infile>>day;
infile.ignore(1000,'/');
infile>>year;
infile.ignore(1000,'/');
cout<<month<<" "<<day<<" "<<year;//debugging


system("PAUSE");
return 0;
}

When I compile this it gives me an error at the "if" statement where I'm checking to see if the file opened. If I take out that whole if statement, my output is 0 0 0, leading me to believe that the file isn't opening for some reason. Is it something wrong with the code?

Recommended Answers

All 11 Replies

Site rules "CODE TAGS".
Few things wrong, no need for system("pause"); C++ has it's own input tools, you never close() the file very BAD!, why do you need exit()?

ifstream infile;
infile.open("file");
if(infile.is_open())
{
   do stuff here;
   
   infile.close();
}
else 
{
    cout << "Error occured." << endl;
}

1. Try to avoid exit function in C++ programs. Use return 1; to exit from main on errors.
2. Library names are placed in namespace std. You must open these names visibility by using directive ( using namespace std; ) or using declaration ( using std::ifstream; ).
3.

std::ifstream infile("input.txt");
if (! infile) {
    std::cout << "Can\'t open..." << std::endl;
    return 1;
}

Don't forget to terminate a line (use endl or at least '\n').
4. You have TWO slashes in a date, why you ignore upto slash THREE times?

I put the system pause in there for debugging purposes, because I have to be able to see if it couts the date at the end there. The exit() thing was basically something I had written down in notes from a C++ class. I don't know what its for either.

So, I took your advice, and this is what my code looks like now.
------------------------------------------
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <cstring>


int main()
{
int month=0, month2=0, day=0, day2=0, year=0, year2=0;
ifstream infile;
infile.open("input.txt");
if(infile.is_open())
{
infile>>month;
infile.ignore(1000,'/');
infile>>day;
infile.ignore(1000,'/');
infile>>year;
infile.ignore(1000,'/');
cout<<month<<" "<<day<<" "<<year;//debugging

infile.close();
}
else
{
cout << "Error occured." << endl;
}

system("PAUSE");
return 0;
}
--------------------
When the black execution screen pops up I get "Error occured"

There IS a file called input.txt in the same folder as this program. And all it has is the date 11/2/2007.

The program and the input.txt file are both on a flash drive, does that make a difference? I don't think it should.

Why people insist on using system("pause") I just don't know, especially when you can just use cin.get() or cin.ignore() If you insist on having a function thats identical, here you go ;) :

#include <iostream>
#include <windows.h>

void Pause(char *message = "Press any key to continue . . . ") {
  std::cout << message;
  HANDLE hStdin; 
  DWORD cNumRead; 
  INPUT_RECORD irInBuf[1]; 

  if ( HANDLE(hStdin = GetStdHandle( STD_INPUT_HANDLE )) == INVALID_HANDLE_VALUE )
    return;

  while ( true )  { 
    if (! ReadConsoleInput( hStdin, irInBuf, 1, &cNumRead) )
      return;

    for (DWORD i = 0; i < cNumRead; ++i)
      if ( irInBuf[i].EventType == KEY_EVENT && irInBuf[i].Event.KeyEvent.bKeyDown ) {
        std::cout << '\n';
        return;
      }
  }
}

But, just stick to cin.ignore() :icon_cool:

I "insist" on using system "pause" because thats just the way I learned it. Feel free to show me a better way that pauses the execution screen that pops up so that i can check for debugging purposes.

The namespace thing was a rookie mistake. I can't believe I missed that. Here's the updated code:
-----------------------------------------
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

int main()
{
int month=0, month2=0, day=0, day2=0, year=0, year2=0;
ifstream infile;
infile.open("input");
if(infile.is_open())
{
infile>>month;
infile.ignore(1000,'/');
infile>>day;
infile.ignore(1000,'/');
infile>>year;
infile.ignore(1000,'/');
cout<<month<<" "<<day<<" "<<year;//debugging

infile.close();
}
else
{
cout << "Error occured." << endl;
}

system("PAUSE");
return 0;
}
---------------------------

Compiled, no errors. Executed... black screen pops up and says Error occured once again.

I'm going to try changing file names or maybe putting it into a different folder, or perhaps using the whole file path. Because for whatever reason its not opening it.

The only other thing I can think of that would be wrong is maybe there is something wrong with the if statement that is making it not true. I can't think of what though.

Don't forget to terminate a line (use endl or at least '\n').
4. You have TWO slashes in a date, why you ignore upto slash THREE times?

I think the last one is supposed to be \n, because when I expand it, there should be a list of lines where the first block of text is mm/dd/yyyy "extra numbers and symbols". Nice catch though, I'll change it. By the way, thats why I have declared month2, day2, and year2, because eventually I want to be able to compare dates.

>Feel free to show me a better way that pauses the execution screen that pops up so that i can check for debugging purposes.

I just did :icon_confused:


>Site rules "CODE TAGS".

I see you decided to ignore that rule then?

1. Always test input result, for example:

if (infile >> month) { // that's ok
    ...
} else {
   // Not-a-number, eof or i/o error
}

2. Use code tag to post code snippets:
[code=c++] sources

[/code]
3. Probably more robust text file input method:

std::string line;
std::istringstream is;
while (std::getline(file,line)) { // read a line
    is.str(line);   // attach a line to stringstream
    is.seekg(0); // get from the beginning 
    if (is >> month) ... // read stringstream
    ... // no need to ignore upto '\n'
}

Sorry about not using tags, I'll use them from now on (I'm new to the forum).

@ArkM: I'll probably take your advice into consideration, but one question. In the get line function... whats "file" supposed to be? I would assume that its supposed to be whatever my file is, but don't I have to declare it above (or is it assumed to already be declared?)

I also don't understand what "is >> month" is supposed to test. Can you explain that better please?

In general though, wouldn't the problem be that the file isn't opening for some reason? It's reading "error occurred" because those are the commands under "else" (meaning the if statement isn't true).

The std::getline function wants the 1st parameter of std::istream type so it's OK to pass std::fstream argument. Of course, file var in the snippet may be your infile.

Overloaded input operator >> returns std::istream& value (const reference to the input stream). That's why it's possible to chain input list:

stream >> a >> b; // treated as
// (stream >> a) >> b =>
// (input a then return reference to stream) >> b =>
// (dereference istream& to stream) >> b =>
// (stream) >> b
// stream >> b

There is a conversion from stream to bool (it's the other story what's this conversion mechanism, see http://faqs.cs.uu.nl/na-dir/C++-faq/part07.html, for example). If a stream is in good state then the conversion yields true, bad, eof of fail state returns false. That's why these constructs are valid, clear and simple:

if (infile) { // OK, input possible
...
while (infile >> word) { read word by word
...

There are lots of reasons to fail on file open operation: no such file (file name misprinted, file erased and so on), file access denied, disk error etc...

Guys, I just wanted to say. Thanks for helping me with this issue. I finally got it fixed.

I'm using Dev C++ and for some reason when I would go "Compile & Run" or "Run", within the editor, it would give me the "Error Occurred" message I said it did. But when I went to the folder and actually clicked on the executable, it worked perfectly fine. I still don't know why it works like that, but it works... so I'm happy.

@Ark: I still don't completely understand why what you did works. I think I'm a Computer Science class away from getting what you are saying. In any case, the way I did it worked. I still appreciate the help though.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.