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



我的问题是在system()中使用字符串。正如你可能知道的,你可以在c++中使用控制台命令system()(或system_(),如果你真的想:|)我想做一个简单的Texteditor,用户可以粘贴一个文件路径,然后直接在控制台中编辑文件。(出于学习目的)我只是通过std::cin获取字符串,然后将其抛出到system()中,以便通过"cd&quot进行目录更改。这行不通,因为没有理由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;
}

我真的不知道我还能尝试什么,因为我对编程比较陌生,所以我很感激你的帮助:)

我把字符串搞砸了。thx。

一个更严重的问题是,我的代码的整个目的都是废话,我读了gm关于母进程和子进程的评论后才明白。我对c++控制台应用程序的理解严重不足,因为我不知道控制台和程序是两个不同的线程。感谢通用的知识。我会想办法解决的。我的问题可能已经有解决办法了。

这是一个该死的函数。名字是……保持自己……SetCurrentDirectory (): |

您可能必须通过c_str()函数将std::string转换为c_string(注意单引号/双引号)。

string doc = file + "/" + filename;
doc = "cd " + file;
system(doc.c_str());

还检查system的返回值可能会对您有所帮助。如果一切正确,它应该返回一个0值。所以你可以直接输入

string doc = file + "/" + filename;
doc = "cd " + file;
if(system(doc.c_str()))
std::cout << "ERRORn";

(更新)

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

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;

}

相关内容

最新更新