OpenMPI C language scanf does not stop taking inpu

2019-07-29 11:15发布

I am trying to run the following MPI code. The problem is with the scanf. The command keep on taking input and does not anywhere. It is supposed to take one input string only.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>

int main(int argc,char * argv[])
{
    int npes, myrank, length = 10;
    char string[length+1];      // array size changed to length +1 as suggested in comments.
    memset(string, 0, length+1);
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &npes);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

    if (myrank == 0) {
        printf("Please enter the string of length %d or enter 0 to generate string randomly:\n", length);
        scanf ("%10s", string);     // format changed as suggested in comments
        printf("%s\n", string);
    }

    MPI_Finalize();
    return 0;
}

Output:

enter image description here

Platform: Mac OS X 10.10

MPI Version : Open MPI: 1.8.3

System Info: Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.0.0 Thread model: posix

Please correct me if I am wrong somewhere.

1条回答
老娘就宠你
2楼-- · 2019-07-29 11:56

Reading from stdin is generally inadvisable in MPI programs due to the complexities of forwarding the input to all of the processes. It's not something that will be portable between different implementations.

Usually, the way people get input for their applications is to read input files. That works everywhere and all you have to do is make the file available at all processes.

查看更多
登录 后发表回答