【问题标题】:What's wrong with deleting a file?删除文件有什么问题?
【发布时间】:2021-05-03 08:56:04
【问题描述】:

我想删除密码为小写字母的txt文件。

创建文件代码:

FILE *files[20];
            char filename[20];
            sprintf(filename, "%d.txt", i);
            files[i] = fopen(filename, "w");

            
            string login, pass;
            //wprowadzanie zmian w licznie kont
            fstream liczb;
            liczb.open("liczbakont.txt", ios::out);
            liczb<<i;
            //tworzenie plików dla poszczególnych kont
            fstream plik(to_string(i)+".txt");
            plik<<"\n";
            cout<<"Podaj login: "<<endl;

删除:

cout<<"pass: "<<endl;
            cin>>pass;
            if(islower (haslo[0]) )
            {
                if( remove(to_string(i)+".txt") == 0)
            }

怎么了?

[错误] 无法将参数 '1' 的 'std::basic_string' 转换为 'const char*' 到 'int remove(const char*)' [错误] '}' 标记之前的预期主表达式 [错误] '}' 标记之前的预期声明

【问题讨论】:

  • remove 想要一个 c 字符串 (const char *) 而不是 std::string。但是to_string() 返回一个std::string。您可以使用 std::string::c_str() 函数从 std::string 获取 c 字符串。
  • 如果您查看错误消息,它说remove 的参数必须是const char *。这是因为remove确实是一个C函数,它对std::string这样的C++对象一无所知。
  • @JohnnyMopp 那么我需要更改或添加什么?

标签: c++


【解决方案1】:

看看你调用的函数的声明:

int remove( const char* fname );

特别注意参数的类型。它是const char*。您用作参数的表达式to_string(i)+".txt" 的类型不是const char*。类型为std::string

您不能将一种类型的参数传递给期望另一种类型的参数的函数 - 除非前一种类型可以隐式转换为后者。 std::string 不能隐式转换为 const char*。这是错误消息告诉您的内容:

[错误] 无法将参数 '1' 的 'std::basic_string' 转换为 'const char*' 到 'int remove(const char*)'

std::string 确实有一个成员函数c_str,它返回一个const char*。现在查看std::remove 的声明,您会发现它与参数的类型匹配。因此,一个简单的解决方法是:

std::remove((to_string(i)+".txt").c_str())

更好的是,我建议改用std::filesystem

std::filesystem::remove(to_string(i)+".txt")

[错误] '}' 标记之前的预期主表达式 [错误] '}' 标记之前的预期声明

此错误告诉您您的 if 语句格式不正确。示例:

// wrong
{
    if(condition)
}

// correct
{
    if(condition)
        statement;
}

【讨论】:

  • [错误] 'std::fstream' 没有名为 'remove' 的成员
  • @KarolPawlak 再次阅读答案。
【解决方案2】:
  • 预期和实际参数的类型似乎不匹配。您可以使用c_str()std::string 获取const char*
  • if 语句之后没有语句,因此它调用第二个错误。添加一些语句来执行或删除额外的if 语句。

添加一些语句(在这种情况下为空语句;):

            if(islower (haslo[0]) )
            {
                if( remove((to_string(i)+".txt").c_str()) == 0);
            }

去掉多余的if:

            if(islower (haslo[0]) )
            {
                remove((to_string(i)+".txt").c_str()) == 0;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    相关资源
    最近更新 更多