Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Reading input from command line C++, instead of sscanf

  • 07-03-2013 11:05AM
    #1
    Closed Accounts Posts: 46


    Hey,

    Last semester we studied C Programming and now we are studying C++.

    We are doing a program that compares two files, the two files are specified on the command line, I completed this program fine with C.

    In C Programming, I was able to read the file names in with sscanf using the following code:
    int main(int argc, char *argv[])
    {
      char fname1[20], fname2[20];
    
     //scan the second argument entered by the user, store it in fname1
    
     sscanf(argv[1], "%19s", fname1); 
     sscanf(argv[2], "%19s", fname2); // scan third argument(other file)
    
    }
    
    

    I am not sure how best to implement the above step in C++, looking online there are some suggestions of using stringstream..but I can`t figure it out.

    Any ideas you may have would be a great help.. Thanks :)


Comments

  • Registered Users, Registered Users 2 Posts: 7,157 ✭✭✭srsly78


    Use cin.

    http://www.cplusplus.com/reference/iostream/cin/

    You can still use the stuff the you are used to from C (like scanf and printf etc), but it's better to do things the C++ way.


  • Closed Accounts Posts: 46 Not Easy


    srsly78 wrote: »
    Use cin.

    http://www.cplusplus.com/reference/iostream/cin/

    You can still use the stuff the you are used to from C (like scanf and printf etc), but it's better to do things the C++ way.

    That didnt work for me...but thanks..

    What seems to have worked is:
    #include <sstream>
    
    int main(int argc, char *argv[])
    {
    
    stringstream str(argv[1]);
    stringstream str2(argv[2]);
    
    str >> fname1;
    str2 >> fname2;
    
    }
    
    
    


Advertisement