Why does the C scanf function not work in my MEX-file in MATLAB?
2 次查看(过去 30 天)
显示 更早的评论
I have a C MEX-file, and I would like to have that file prompt the user for input when the file is run. To do this, I am using the C scanf function, which reads information from standard input. Here is the relevant code I am using:
printf("Enter number of minutes (0 - 59) = ");
scanf("%d", #_minutes);
However, when this file is executed, the scanf function appears to be ignored, and the rest of the code is executed without waiting for user input.
采纳的回答
MathWorks Support Team
2010-1-22
This bug has been fixed in MATLAB 7.5 (R2007b). For previous product releases, read below for any possible workarounds:
Documentation on using C functions in MEX-files to prompt users for data is missing from the MATLAB external interfaces documentation. Here is additional information on using those functions:
The ability to access stdin or stdout is not available in MATLAB. Avoid trying to use printf and scanf in C MEX-files. To work around this issue:
1. Perform the input in MATLAB code, and design the MEX-file so that you pass the input value to the MEX-file.
2. Use mexCallMATLAB with the MATLAB function INPUT. Here is an example of how to do this:
mxArray *num_minutes, *str;
double out;
/* Replace the following two lines with the two code lines after them:
* printf("Enter number of minutes (0 - 59) = ");
* scanf("%d", #_minutes);
*/
str = mxCreateString("Enter number of Minutes (0 - 59) = ");
mexCallMATLAB(1,#_minutes,1,&str,"input");
/* The following is a test, to make sure we processed the input. */
out = mxGetScalar(num_minutes);
mexPrintf("This is really a double: %.0f ", out);
/* Need to free memory. */
mxFree(num_minutes);
mxFree(str);
0 个评论
更多回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!