LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Problem with else/if and UNtidy program (https://www.linuxquestions.org/questions/programming-9/problem-with-else-if-and-untidy-program-944115/)

spiky0011 05-09-2012 03:13 PM

Problem with else/if and UNtidy program
 
Hi

A few days playing with c++. I,m having trouble with else if,
And a few queries with my program, If any 1 can help with. The program runs and dose what I want
Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
     
        ifstream myFile("/home/spiky/Exercise1/test1/Doc1.txt"); //Do i have to make an entry for each file
        ifstream myFile2("/home/spiky/Exercise1/test1/Doc2.txt"); //Otherwise how?
        string  line;
     

        char Answer;       

        cout << "Which file do you want to open(1=Doc1/2=Doc2)? ";
        cin >> Answer;

        if( Answer == '1' ) // Doc1
                 
 
 
    if (myFile)
    {
        while (getline(myFile, line))
        {
            cout << line << endl;
        }
    }
 
    else  // Tried else if here with the 2nd  part
   
        cerr << "Failed to open Doc1." << endl;

  if( Answer == '2' ) // Doc2
       

  if (myFile2)
  {
      while (getline(myFile2, line))
      {
          cout << line <<endl;
      }       
  }
  else

      cerr << "Failed to open Doc2." << endl; 


        return 0;
}

I put the comments to try to show what I had tried

pan64 05-09-2012 03:35 PM

see man ifstream: http://www.cplusplus.com/reference/i...ream/ifstream/
the line:
if (MyFile)
has no meaning, it will not do what you expect.

dwhitney67 05-09-2012 05:25 PM

Quote:

Originally Posted by pan64 (Post 4674544)
see man ifstream: http://www.cplusplus.com/reference/i...ream/ifstream/
the line:
if (MyFile)
has no meaning, it will not do what you expect.

Sorry, but that is NOT true. The operator bool() method for the stream object will be called; it returns the same value as if the good() method had been called.

dwhitney67 05-09-2012 05:28 PM

Quote:

Originally Posted by spiky0011 (Post 4674526)
I,m having trouble with else if,
And a few queries with my program, If any 1 can help with. The program runs and dose what I want

Try to get into the habit of using curly-braces when you define a block of code (ie. an if-block, a while-loop block, etc). For example:
Code:

if (condition1)
{
    if (conditionOther)
    {
        ...
    }
    else
    {
        ...
    }
}
else if (condition2)
{
    ...
}
else
{
    ...
}

It will be easier for you, and for others to read your code if you follow this simple advice.

spiky0011 05-12-2012 01:06 PM

Hi
The 1st program works ok (there is a problem, It puts a ? in a diamond on the command line). But I would like to know where I,m wrong on the 2nd program.
I have googled but all i can find are using cout to output something, not open a Doc.
I know this is all beginner stuff but thats what I am,
dwhitney67 I have tried to put in to practice from your last post but cant seem to make it work.

Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
     
        ifstream myFile("/home/spiky/Exercise1/test1/Doc1.txt" , ifstream::out ); //Do i have to make an entry for each file
        ifstream myFile2("/home/spiky/Exercise1/test1/Doc2.txt" , ifstream::in ); //Otherwise how?
        string  line;
     

        char Answer;       

        cout << "Which file do you want to open(1=Doc1/2=Doc2)? ";
        cin >> Answer;

        if( Answer == '1' ) // Doc1
                 
 
 
//    if (myFile)
    {
        while (myFile.good ())
        {
            cout << (char) myFile.get();
        }
      myFile.close ();
    }
 
 //  else
   
 //      cerr << "Failed to open Doc1." << endl;

  else if( Answer == '2' ) // Doc2
       

  if (myFile2)
  {
      while (getline(myFile2, line))
      {
          cout << line <<endl;
      }       
  }
  else

      cerr << "Failed to open Doc." << endl; 


    return 0;
 }

Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()


{

        ifstream MyFile("home/spiky/Exercise1/test1/Doc1.txt");
        ifstream MyFile2("~/Exercise1/test1/Doc2.txt");
        ifstream MyFile3("~/Exercise1/test1/Doc2.txt");
        string line;

        char Answer;

        cout << "Which Document do you want to view(1=Doc1/2=Doc2/3=Doc3) ";
        cin >> Answer;



        if ( Answer == '1' )

{
 
          if (MyFile)
          {     


                  while (getline (MyFile, line))
                      { 
                            cout << line << endl;
                      }

           
            }
 
            else
                {
                cerr << "Failed to open Doc1" << endl;
                }
     

{
            else if( Answer == '2' )
 }
 
 
 
      if (MyFile2)
      {


        {
          while (getline (MyFile2, line ))
          {
                  cout << line << endl;
          }

        }


        }

          else
                {                 
                cerr << "Failed to open Doc2." << endl;
                }


      cin.get();
}


millgates 05-12-2012 04:31 PM

Quote:

Originally Posted by spiky0011 (Post 4676758)
Hi
The 1st program works ok (there is a problem, It puts a ? in a diamond on the command line).

You should know that myfile.good() will only return false after you try to read beyond the end of the file. You read and write a character after the end of the file was reached.

As for the second program, your braces are still a mess. You should learn to keep your indentation consistent troughout your code. Then it will be easier for you to spot the errors in your syntax.

Code:

{
            else if( Answer == '2' )
 }

this is a conditional statement without a body enclosed in braces. There should actually be a closing brace there:

Code:

} else if( Answer == '2' )
Also, be careful about ambiguous elses.

if you have something like:

Code:

if(a)
    if(b) {
        ...
    }
else { ... }

I would recommend to allways put explicit braces here. Either:
Code:

if(a) {
    if(b) {
        ...
    }
} else { ... }

or

Code:

if(a) {
    if(b) {
        ...
    }
    else { ... }
}


spiky0011 05-13-2012 06:39 AM

Hi

Ok I have tried looking up indenting the code and that shows various examples, they basically say keep it all the same uniformed
Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()


{
  ifstream MyFile("home/spiky/Exercise1/test1/Doc1.txt");
  ifstream MyFile2("~/Exercise1/test1/Doc2.txt");
  ifstream MyFile3("~/Exercise1/test1/Doc2.txt");
  string line;

  char Answer;

  cout << "Which Document do you want to view(1=Doc1/2=Doc2/3=Doc3) ";
  cin >> Answer;



  if ( Answer == '1' ){


  if (MyFile)
{     

  while (getline (MyFile, line))


    cout << line << endl;
}

           
}
 
  else
{
    cerr << "Failed to open Doc1" << endl;
}
     

} else if( Answer == '2' )
 
 
 
 
  if (MyFile2)
{


       
  while (getline (MyFile2, line ))
{
    cout << line << endl;
}

       


}

  else 
{                 
  cerr << "Failed to open Doc2." << endl;
}

  cin.get();
}

I also cant get my head around why it wont work! It produces the cerr, but wont show the file Doc1 or doc2, where the 1st example runs and shows both Docs as asked for.
I also hope that the Layout is better

dwhitney67 05-13-2012 07:00 AM

My first question... what editor are you using? Your perception of good indentation is not evident after you posted your code. Did you review the code you posted? The indentation is crap.

Look at this:
Code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
  char Answer;

  cout << "Which Document do you want to view(1=Doc1/2=Doc2/3=Doc3) ";
  cin >> Answer;

  if ( Answer == '1' )
  {
    ifstream MyFile("Doc1.txt");

    if (MyFile)
    {
      string line;
      while (getline(MyFile, line))
      {
        cout << line << endl;
      }
    }
    else
    {
      cerr << "Failed to open Doc1" << endl;
    }
  }
  else if( Answer == '2')
  {
    ifstream MyFile("Doc2.txt");

    if (MyFile)
    {
      string line;
      while (getline(MyFile, line ))
      {
        cout << line << endl;
      }
    }
    else 
    {
      cerr << "Failed to open Doc2." << endl;
    }
  }
  else if( Answer == '3')
  {
    ifstream MyFile("Doc3.txt");

    if (MyFile)
    {
      string line;
      while (getline(MyFile, line ))
      {
        cout << line << endl;
      }
    }
    else 
    {
      cerr << "Failed to open Doc3." << endl;
    }
  }
  else
  {
    cerr << "Bad input." << endl;
  }
}

When you see repetitive code, such as shown above, this is a strong clue to refactor the code to use a function to encapsulate the common code (such as to open/read a file). I do not know if you have yet covered functions in your studies, but it is something that I recommend you do today. Also, look into replacing many if-else statements with the use of a switch construct.

spiky0011 05-13-2012 07:36 AM

Ok

I realise this is alot harder than I thought, I picked up on doing this a week ago as a pure past time. I googled and picked up on a few tutorials which work, I thought I could expand on them. (Experimental) Not realiseing things don't quite work as expected.
I did know there would be alot of studying
I,m not trying to rewrite an OS just keep myself amused

I am using vim as the editor


All times are GMT -5. The time now is 12:06 AM.