LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-09-2012, 03:13 PM   #1
spiky0011
Senior Member
 
Registered: Jan 2011
Location: PLANET-SPIKE
Distribution: /LFS/Debian
Posts: 2,511
Blog Entries: 1

Rep: Reputation: 412Reputation: 412Reputation: 412Reputation: 412Reputation: 412
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
 
Click here to see the post LQ members have rated as the most helpful post in this thread.
Old 05-09-2012, 03:35 PM   #2
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,830

Rep: Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308
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.
 
Old 05-09-2012, 05:25 PM   #3
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Quote:
Originally Posted by pan64 View Post
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.
 
Old 05-09-2012, 05:28 PM   #4
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Quote:
Originally Posted by spiky0011 View Post
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.

Last edited by dwhitney67; 05-09-2012 at 05:29 PM.
 
2 members found this post helpful.
Old 05-12-2012, 01:06 PM   #5
spiky0011
Senior Member
 
Registered: Jan 2011
Location: PLANET-SPIKE
Distribution: /LFS/Debian
Posts: 2,511

Original Poster
Blog Entries: 1

Rep: Reputation: 412Reputation: 412Reputation: 412Reputation: 412Reputation: 412
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();
}
 
Old 05-12-2012, 04:31 PM   #6
millgates
Member
 
Registered: Feb 2009
Location: 192.168.x.x
Distribution: Slackware
Posts: 852

Rep: Reputation: 389Reputation: 389Reputation: 389Reputation: 389
Quote:
Originally Posted by spiky0011 View Post
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 { ... }
}
 
Old 05-13-2012, 06:39 AM   #7
spiky0011
Senior Member
 
Registered: Jan 2011
Location: PLANET-SPIKE
Distribution: /LFS/Debian
Posts: 2,511

Original Poster
Blog Entries: 1

Rep: Reputation: 412Reputation: 412Reputation: 412Reputation: 412Reputation: 412
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
 
Old 05-13-2012, 07:00 AM   #8
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
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.

Last edited by dwhitney67; 05-13-2012 at 07:01 AM.
 
Old 05-13-2012, 07:36 AM   #9
spiky0011
Senior Member
 
Registered: Jan 2011
Location: PLANET-SPIKE
Distribution: /LFS/Debian
Posts: 2,511

Original Poster
Blog Entries: 1

Rep: Reputation: 412Reputation: 412Reputation: 412Reputation: 412Reputation: 412
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
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem with a C program vasmakk Linux - Newbie 11 10-25-2009 07:42 PM
a program for the 3x+1 problem rec3g Programming 8 03-30-2008 01:01 PM
program problem megadeth Linux - Software 1 05-24-2005 09:58 PM
su program problem xaos5 Linux - Software 6 03-17-2005 01:02 PM
Problem with C program exvor Programming 27 01-04-2005 11:51 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:58 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration