【问题标题】:cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'int system(const char*) [duplicate]无法将参数 '1' 的 'std::string {aka std::basic_string}' 转换为 'const char*' 到 'int system(const char*) [重复]
【发布时间】:2015-03-13 16:57:57
【问题描述】:

我有以下代码可以作为文件夹锁进行刺激:

#include<iostream>
#include<conio.h>
#include<windows.h>
#include<string>
#include<fstream>
#include<process.h>
#define max 100

using namespace std;

struct folder_all{
       std::string name;
       std::string location;
       };

int main(){
     folder_all folder[max];
     int n;

     cout<<"\n\n\t\t\tFolder Locker"<<endl;

if (std::ifstream("data"))
{

cout<<"\n\n\tYour Folders are safe with us"<<endl;
cout<<"Enter your password to unlock(Password will not be visible): ";

HANDLE inHandle = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(inHandle, &mode); 
SetConsoleMode(inHandle, mode & ~ENABLE_ECHO_INPUT);

std::string inpass;
cin>>inpass;

SetConsoleMode(inHandle, mode);

}
else{
     cout<<"\nNo. of folders to be locked: ";
     cin>>n;
HANDLE inHandle = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode; 
GetConsoleMode(inHandle, &mode); 
SetConsoleMode(inHandle, mode & ~ENABLE_ECHO_INPUT);

//read the password
std::string password;
cout<<"\nEnter the password(password will not be visible): ";

cin>>password; 

/
SetConsoleMode(inHandle, mode); 
cout<<"\n\n"<<endl;
     for(int i=0; i<n; i++){
            cout<<"Enter folder "<<i+1<<" details:"<<endl<<endl;
            cout<<"Folder Name: ";
            cin>>folder[i].name;
            cout<<"Folder Location: "<<endl<<"\tEnter in following format 'Drivelabel://parent-folder/child-folder/folder'"<<endl;
            cout<<"\tfor example C://desktop/pics/your-folder"<<endl;
            cin>>folder[i].location;
}

 std::ofstream o("data");

      o <<password<<std::endl;
      for(int j=0; j<n; j++){
        o<<folder[j].location<<std::endl;
      }
system("attrib +h +s +r data");

std::string fold;

for(int k=0; k<n; k++){
       std::string f = folder[k].location ;
   fold = "attrib +h +s +r " + f + " ";
    system(fold); //this line gives me a error
}
cout<<"\nYour folder/s have been locked"<<endl;
cout<<"\nThis application will now exit"<<endl;
exit(0);

  }
}

代码要求用户输入密码,然后将其保存在文件数据中并隐藏文件。当用户输入要锁定的文件夹的位置时,它也会隐藏它。但对于 1 个错误,它无法正常工作 错误是:

main.cpp|79|error: 无法将参数 '1' 的 'std::string {aka std::basic_string}' 转换为 'const char*' 到 'int system(const char*)'|

如何解决?

【问题讨论】:

  • 如果您只是阅读它,该错误应该是不言自明的。
  • 对于一个微不足道的问题,这是很多主要不相关的代码。你真的应该尝试构建一个 MCVE。
  • 系统采用char* 而不是std::string。使用fold.c_str()char* 传递给system()

标签: c++


【解决方案1】:

使用c_str() 方法:

system(fold.c_str());

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2014-07-13
    • 1970-01-01
    • 2015-01-03
    • 2023-03-21
    • 2017-03-10
    • 2021-10-28
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多