c++ 在system()中使用字符串(可能是system_())

yrdbyhpb  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(203)

我的问题是在system()中使用了一个字符串。正如你所知,如果你真的想,你可以在c++中使用system()(或system_())的控制台命令:|)我想做一个简单的Texteditor,用户可以粘贴一个文件路径,然后直接在控制台中编辑文件。(为了学习的目的)我只是通过std::cin获得字符串,然后将其扔入system(),以便通过“cd”更改目录。嗯,这不起作用,因为system()没有理由需要一个const char指针作为参数。在通过“.data()”转换字符串并将指针粘贴到system()函数中后,它不会更改目录,也不会抛出错误或崩溃
'

#pragma once

#include <Windows.h>
#include <fstream>
#include <iostream>
#include <ostream>
#include <istream>
#include <string>

using std::fstream;

using namespace std;

int start_doin_da_stream(string h, string filename) {

    //now the parsing of the content into the cmd-shell shall beginn

    system("color 1b");
    string file = h;

    //changing directory
    string doc = file + '/' + filename;
    doc = "cd " + file;

    //maybe the issue
    char const* foo = doc.data();
    //

    system(foo);
    system("dir");

    //creating a file stream
    fstream stream(filename, std::ios::out | std::ios::app);

    //checking for living stream
    bool alive = true;
    if (alive != stream.good()) {
        std::cout << "my men... your file deaddd!!!";
        return 0;
    }
    else
    {
        std::cout << "Its alive yeahhhhhh!!!!!";
        std::this_thread::sleep_for(std::chrono::milliseconds(100000));
    }

    //if alive true gehts weiter ans schreiben in die Konsole

    return 0;
}

'
我真的不知道我还可以尝试什么,因为我对编程比较陌生,所以我很感激你的帮助:)
我搞砸了绳子,谢谢你们.
一个更严重的问题是,我的代码的整个目的是无意义的,我理解后,阅读通用汽车的评论母亲和儿童进程。我的理解c++控制台应用程序是严重缺乏,因为我不知道,控制台和程序是2个不同的线程。感谢通用汽车为您的知识。我会尝试得到一个变通办法。可能有一个解决方案,我的问题已经。
这是一个该死的函数。名称是...保持... SetCurrentDirectory():|

gtlvzcf8

gtlvzcf81#

你可能需要通过函数c_str()把你的std::string转换成c_string(注意单引号/双引号)。

string doc = file + "/" + filename;
doc = "cd " + file;

system(doc.c_str());

检查system的返回值也会对你有帮助。2如果一切都正确的话,它应该返回一个0值。3所以你可以这样做

string doc = file + "/" + filename;
doc = "cd " + file;

if(system(doc.c_str()))
    std::cout << "ERROR\n";

[更新]
由于提供的代码有点奇怪,这可能是一个更具体的解决方案

int start_doin_da_stream(string path, string filename) {

//now the parsing of the content into the cmd-shell shall beginn
system("color 1b");

//changing directory
string file_path = "cd " + path;
system(file_path.c_str());

//creating a file stream
fstream stream(filename, std::ios::out | std::ios::app);

//checking for living stream
bool alive = true;
if (alive != stream.good()) {
    std::cout << "my men... your file deaddd!!!";
    return 1; // you might want something different from 0 in order to debug the error
}
else // this else is not wrong but avoidable since the true condition has a return statement
{
    std::cout << "Its alive yeahhhhhh!!!!!";
    std::this_thread::sleep_for(std::chrono::milliseconds(100000));
}

//if alive true ghets weiter ans schreiben in die Konsole

return 0;

}

相关问题