Using standard io stream:stdin and stdout in a matlab exe

不想你离开。 提交于 2019-12-01 06:09:38

Let me illustrate with a toy example. Consider the following MATLAB function:

greet.m

function greet()
    str = input('Enter your name: ','s');
    fprintf('Hello %s\n',str)
end

Now lets compile it into a standalone application. Note that if you use the deploytool tool, make sure to choose "Console application" NOT "Windows standalone application" as target. The latter apparently produces an executable where the standard input is connected to the system shell not the MATLAB command prompt..

If you prefer to directly compile it yourself, use the following invocation:

mcc -o hello -W main:hello -T link:exe -N -v greet.m

(For reference, the "Windows app" target issues -W WinMain:hello instead)

Running the executable produces:

C:\> hello
Enter your name: Amro
Hello Amro

where the input from the keyboard is correctly handled.

It turns out that input reads the standard input stream.

The reason why I failed to collect my inputs, is because I was using it as follows:

input('prompt','s')

As a result the string 'prompt' was sent to the program calling my application, and as it considered this an invalid response/request it did not send anything.

I have succeeded in making a small test program, and unlike I suspected before it is NOT a problem that the other application doesn't hit enter after sending a command.

The general solution

This is the way I have my current setup,

while 1
   stdin = input('','s'); % Note the empty first argument
   if ~isempty(stdin)
    stdout = process_input(stdin);
    stdout % Displaying the result (And thus sending it to stdout)
   end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!