Endorphinex Endorphinex - 20 days ago 6
C++ Question

Some problems with c++ code

My code:

#include <iostream>
#include <string>
#define CMDUSAGE "Usage: NX [/f file]\n\n /f file Specifies *.nx file to be read by interpreter.\n"

using namespace std;

int main(int argc, char* argv[])
{
if (argc == 1)
{
printf(CMDUSAGE);
return 1;
}
else
{
for (int i = 1; i <= argc; i++)
{
cout << "Argument " << argv[i] << endl; //Debug
if (strcmp(argv[i], "/f")) //This always gives 'false'
{
if (argc > i)
{
cout << "argc > " << i << endl; //Debug
}
else
{
cout << "Expected a value for switch '/f'." << endl;
cout << CMDUSAGE;
return 1;
}
}
else
{
cout << "Unrecognized option " << argv[i] << "." << endl;
cout << CMDUSAGE << endl;
//return 1;
}
cout << "I'm about to leave 'for' loop!" << endl; //Debug
} // <-- Here it crashes
cout << "I won't be printed..." << endl; //Debug
}
cout << "I won't be printed too!\n" << endl; //Debug

cout << "return 0;" << endl; //Debug
return 0;
}


Problems:


  • Fixed When my application is started through the cmd, it gives me following output:

    Argument /f


    Unrecognized option /f.


    Usage: NX [/f file]




    /f file Specifies *.nx file to be read by interpreter.




    I'm about to leave 'for' loop!


    Argument test


    argc > 2


    I'm about to leave 'for' loop!


    Argument



    ...and then it shows "Program has stopped working" window.

  • Debugging my app from Visual Studio 2015 Update 2 with additional arguments specified in Project > Project Properties... > Configuration Properties > Debugging > Command Arguments always sets
    argc
    to 1. Same thing happens if there aren't any arguments specified.

    If I run this small and problematic application from cmd, it sets
    argc
    to real count of arguments, and then happens everything what I said in first point.

  • Fixed
    strcmp(argv[i], "/f")
    always returns
    false
    . I don't know why it happens, and how to properly compare two strings.



Any suggestions will be highly appreciated.

Answer

You have an index out of bounds and wrong starting position for the counter, so instead:

for (int i = 1; i <= argc; i++)

it should be:

for (int i = 0; i < argc; i++)

Fix the strcmp as pointed in comments above so that instead of:

if (strcmp(argv[i], "/f"))

you have:

if (strcmp(argv[i], "/f") == 0)

That would eliminate the nasty 0xC0000005: Access violation reading location 0x00000000 exception you were receiving.