-
system() function using
hello ..
i m new at c++ programming. i have a problem about system() using.
you know system( ) function lets us to use dos commands.
and i have to use it like
system("dir")
my problem starts here. i want to use commands with variable.
for ex :
Code:
char folder[10] ;
.
cout<<"which folder"<<endl; // for ex i typed " photos " ;
cin>>folder;
.
system("dir folder[10]") // here is my problem.
i can not use system function with variable. i want to use that function to effect the folder i choose. but system function does what is written between quotation marks. So it's looking for the folder named "folder[10]" . i want it to effect the photos folder.
so here are my questions ;
how can i use system function with variable ?
or is there anyway to use dos commands for the variables (folders) i choose ?
or is there any other way to do this ?
i m newbie.. i will be glad if someone can help, any help would be appreciated.
Thanx in advance.
-
1. stop using C-strings, use std::string
2. do not use >> to read input - it stops on spaces, so you cannot read folder name with spaces inside - use getline
3. use stringstream to generate result
Code:
std::stringstream ss;
ss<< "dir " << folder;
system(ss.str().c_str());
-
Well, you can use sprintf/snprintf/strings/stringstreams to accomplish this.
Using strings:
Code:
string command = "dir ";
string folder;
cout << "which folder" << endl;
cin >> folder; // Type in "photos"
command += folder; // Now command contains "dir photos"
system(command.c_str());