Click here to Skip to main content
15,922,166 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi..
I want to know how i'm going to wrote a simple C++/C application that accept value in the first place.

For example..my Application name will be "myCommand" and my value is "50". I will wrote in the command line something like this in unix base "myCommand 50".
then my code will receive the value "50" from the command line then it will print back the value

the original code :

C++
#include <stdio.h>

main() {
int count;
puts("Please enter a number: ");
scanf("%d", &count);
printf("The number is %d \n", count);
} 


Please help ??
Posted
Updated 25-Mar-13 19:13pm
v2

1 solution

Ummm ... Is this a trick question?

C++
#include <iostream>

using namespace std;

int main( int argc, char* argv[] )
{
  cout << "Program name: " << argv[0]
       << "\nArgument: " << argv[1]; << "\n";
  return 0;
}


It sounds like you probably want to call ShellExecute() or a related API with argv[1].

[Edit]You editted your question so that it now asks something different; however I think my answer still answers the updated question. Just ignore the "ShellExecute() part.[/Edit]
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 26-Mar-13 1:17am    
Right, a 5.
—SA
H.Brydon 26-Mar-13 1:25am    
Thank you SA. What goes around comes around!
bunge-bunge 26-Mar-13 1:26am    
Thank H.Brydon.
You have point me out the way.
I have changed my scenario in my question for you to understand more about what i really mean
Stefan_Lang 28-Mar-13 5:27am    
H.Brydon is correct. Once you've started the program, the input stream will jump to the next line. So you can no longer read the additional information from the command line through standard input functions. The _only_ way to retrieve additional arguments from the command line is by accessing argv and argc!

Of course, if your intention is a dialog-based input, as the code you posted suggests, then it doesn't make sense to write "myCommand 50", because that skips over the programs request to enter a number! In that case you'd start your program with just "myCommand", which in turn will print "Please entere a number", and only then you'll type "50".

Tl;dr:
If your intention is to just pass the value to your program dirctly, use H.Brydons code. If you wish to interact with the user by querying the value, then use your own code, and start your application just with "myCommand".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900