tags:

views:

62

answers:

3

Recently, I figured out that Xcode could be used to write normal C++ programs.

My problem is with the following code :

#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char *argv[]) {
    char operation='0';
    int operand=0;
    //open file for reading  
    ifstream ifile;
    ifile.open (argv[1]);
    if(!ifile.is_open()){
            cout<<"Invalid file\n";
            exit(1);
    }
    while(ifile.good())
    {
            ifile>>operation;

            if(operation=='I') {  
                    ifile>>operand;
                    cout<<"Inserting :"<<operand<<endl;
                                                    }
            else
            if(operation=='D') { cout<<"Deleting  "<<endl;
                                                    }
    }
    return 0;
}

When the input is the following ,

I 4
I 8
I 10
I 9
*

When I compile and run in Xcode , I get the following

Loading program into debugger…
Program loaded.
run
[Switching to process 58116]
Inserting :0
Running…

Debugger stopped.
Program exited with status value:0.

I have set the filename as an argument in the project preferences.

However, in the Terminal , I get

Inserting :4
Inserting :8
Inserting :10
Inserting :9

Please help me understand why this happens.

A: 

You probably need to specify an absolute path in your project preferences argument.

Karl Bielefeldt
That's just asking for trouble… if the file is in the project directory, its path should be project-relative.
Potatoswatter
A: 

First as a standard rule when debugging. Eliminate all unnecessary complexity

I suspect your problem is that you are not correctly specifying argv[1] in your debugging parameters, but I could be wrong.

First, try manually specifying the filename rather than accepting it from argv[1]. (The relative path should be from your 'project/build/Debug' directory)

You need to check ifile.good() after you attempt to read the byte, only then would you know if EOF was hit while reading.

Lastly, always check argc when reading argv[].

Akusete
I removed the check of _argc_ when posting here. The file path is _/ads/test.txt_ , and is output correctly by `cout<<argv[1]` . In addition, the first `I` is read , resulting in `Inserting :0` output, so I think that the file is open. Anyways, I just passed the filename instead of `argv[1]` and get the same output.
Prithvi
A: 

Use "Edit Active Executable" to access the settings for working directory and command-line arguments.

XCode unfortunately has a few redundant project settings, and you need to open the right window.

Potatoswatter
Yes, I have put it right there , hardcoding the filename does not work either.
Prithvi