Passing variables to system function in C [duplica

2020-04-12 03:14发布

I have this C code:

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

int main()
{
    int a;

    printf("Please enter a number:\n");
    scanf("%d",&a);
    printf("Your number is: %d\n",a);
    system("echo %d",a);
}

I'm interested in the last command, the system() function and why I can't print my variable like i printed it with printf(). I want to be able to ask the user some input , let's say a string and then pass it to the system function.

Practical example:

Ask user for folder name

system("mkdir %s", FolderName);

Thank you in advance! :)

3条回答
forever°为你锁心
2楼-- · 2020-04-12 03:23

The System function doesnt have the formatting options like printf, instead the system function takes a C string as a parameter.

Check out the following site for more info.

http://www.tutorialspoint.com/c_standard_library/c_function_system.htm

查看更多
贪生不怕死
3楼-- · 2020-04-12 03:39

system, unlike printf does not accept multiple parameters, it only accepts one parameter, a const char *command. So you need to build your complete command string first in memory and then pass it to system.

An example would be:

char buf[32];
sprintf(buf, "echo %d", a);
system(buf);

You need to take care not to write more chars into buf than buf has space for. You might want to read the man page for snprintf to rewrite the code in a safer way.

Also: if your code really compiled, then please compile with a higher warning level. At least that would have given you warnings that you are calling system with more parameters than you should.

查看更多
放我归山
4楼-- · 2020-04-12 03:41

Use snprintf

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

int main()                                                                     
{                                                                              
    int a;                                                                     
    char buf[BUFSIZ];                                                          

    printf("Please enter a number:\n");                                        
    scanf("%d",&a);                                                            
    printf("Your number is: %d\n",a);                                          
    snprintf(buf, sizeof(buf), "echo %d",a);                                   
    system(buf);                                                               
}  
查看更多
登录 后发表回答