如何在C++中从命令行读取参数?
我目前有以下代码:
int data_size = 0;
std::cout << "Please enter an integer value: ";
std::cin >> data_size;
std::cout << "The value you entered is " << data_size;
主要:
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;
}
它有效,但一直要求我输入一个整数值4次
然后当我输入一个数字时,命令行冻结。
这是我在命令行中得到的
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:
最佳答案
对于MPI程序,用std::cin
读取内容不是一个好主意。我不知道您如何使它那样工作,而您不应该这样做。
不过,您可以选择以下方法:
如果您的代码输入足够小,可以作为命令行参数传递,请这样做。在您的示例中,您的输入代码块将变为
// Do some error handling if needed, then
int data_size = std::atoi(argv[1]);
然后像这样开始工作
mpiexec -n 4 .\DistributedSystems.exe k
k
是您想要的data_size
的号码。如果要达到这样的方便程度,请输入大量文件,将其写入文件并按上述传递输入文件名。然后,每个进程都可以使用自己的
std::ifstream
打开该文件,并从那里读取数据。根据Rob Latham,此工作是特定于实现的行为。但是,如果您的系统使用命令行界面,则通常可以期望它能正常工作。