How do I read arguments from the command line in C++?
I currently have this code:
int data_size = 0;
std::cout << "Please enter an integer value: ";
std::cin >> data_size;
std::cout << "The value you entered is " << data_size;
Main :
int main(int argc, char** argv) {
int data_size = 0;
std::cout << "Please enter an integer value: ";
std::cin >> data_size;
std::cout << "The value you entered is " << data_size;
// initialise the MPI library
MPI_Init(NULL, NULL);
// determine the world size
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// determine our rank in the world
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
std::cout << "rank " << world_rank << " size " << world_size << std::endl;
if (world_rank == 0){
coordinator(world_size);
}
else{
participant(world_rank, world_size);
}
MPI_Finalize();
return 0;
}
It works but it keeps asking me to enter an integer value 4 times then when I enter it a number it the command line freezes.
here is what i get in the command line
C:\Users\Roland\Documents\Visual Studio 2013\Projects\DistributedSystems\Debug>m
piexec -n 4 .\DistributedSystems.exe
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
With MPI programs, reading stuff with std::cin
is not a good idea. I have no idea how you could make it work that way and you just shouldn't.
Here are your alternatives though:
If the input to your code is small enough to be passed as command line argument, do so. In your example, your input code block would change to
// Do some error handling if needed, then
int data_size = std::atoi(argv[1]);
and the start the job like
mpiexec -n 4 .\DistributedSystems.exe k
with k
being the number you want data_size
to be.
If you should get to a point where the amount input is to large for convenient use like this, write it in a file and pass the input filename as above. Then, every process can open that file in its own std::ifstream
and read the data from there.
According to Rob Latham , this working is an implementation specific behavior. You can however generally expect this to work if your system uses a command line interface.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.