Inserting string s into quotation marks

Write your question here.


Hi, I was trying to make a program where it opens certain files on a drive using the command prompt. Everything seems fine except for the fact I cannot for the life of me figure out how put string s (the file the user wants to open) into system("") without the command prompt just printing "s" since its in quotation marks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
	string s;
	system("cmd.exe /c dir c:");
	cout << "Please enter the file you would like to open: ";
	getline(cin, s);
	system("s");

return 0;
}










Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
   string s;
   system("cmd.exe /c dir c:");
   cout << "Please enter the file you would like to open: ";
   getline(cin, s);
   system( s.c_str() );
}


I can't recommend the method, though. It would be better doing it straight from the command line, or using a batch file.
closed account (48T7M4Gy)
It's not 100% clear what you are trying to do. The following program runs in the console/terminal and opens a file (doesn't execute it), then displays the contents.

At the prompt type open filename e.g. open myprogram.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>

int main (int argc, char* argv[]) {
    std::string line;
    std::ifstream myfile ( *argv );
    
    if (myfile.is_open())
    {
        while ( getline (myfile, line) )
        {
            std::cout << line << '\n';
        }
        myfile.close();
    }
    
    else
        std::cout << "Unable to open file";
    
    return 0;
}
Last edited on
Thanks for the feedback! I understand now that this is definitely not the best way of going about this, but I was mainly trying to experiment with some of the things I knew. I now also see some of the major flaws in my code, I'm grateful for your time.
Topic archived. No new replies allowed.