C++,我使用 Vector 中的函数 at(),但我有问题

-1 c++ overloading compiler-errors vector c++11

向量中的问题

cannot convert '__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> >, std::__cxx11::basic_string<char> >::value_type' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'gcc
Run Code Online (Sandbox Code Playgroud)

真诚地,我不知道为什么以及如何纠正这个问题。

#include <stdio.h>
#include <conio.h>
#include <string>
#include <vector>

namespace anas 
{  
    void passwordGenerator() 
    {
        std::vector<std::string> PasswordString;

        std::string ElencoAlfabeto("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
        char CharAlfabeto[ElencoAlfabeto.length()];

        for (int Lettere_Create = 0; Lettere_Create < 8; Lettere_Create++)  
        {
            int             NumeroCarattere     = rand() % sizeof(CharAlfabeto);
            CharAlfabeto   [NumeroCarattere]    = ElencoAlfabeto[NumeroCarattere];
            
            PasswordString.push_back(CharAlfabeto[NumeroCarattere]); 
        }

        for (int Lettere_Scritte = 0; Lettere_Scritte < 8; Lettere_Scritte++)
        {
            printf (   PasswordString.at(Lettere_Scritte)    );
        }
    }
}

int main()
{
    system("cls");
    std ::printf("the program is started... \n \n");
    anas::passwordGenerator();
}
Run Code Online (Sandbox Code Playgroud)

输出应该是一个随机的 8 个字母生成器。


是的,这是我第一次使用vector......这里是我使用的文章:矢量文章文档

当我将鼠标光标放在 上时at,我看到 1 过载,什么是平均过载? 过载错误

Ben*_*igt 5

在这一行

printf (   PasswordString.at(Lettere_Scritte)    );
Run Code Online (Sandbox Code Playgroud)

该函数printf需要一个,const char*但你给它一个std::string

除了类型不匹配之外,您永远不应该传递任意数据作为 的第一个参数printf,因为它会尝试解释格式代码。

如果你真的想使用printf,这会起作用:

printf( "%s", PasswordString.at(Lettere_Scritte).c_str() );
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令完全跳过格式代码解码puts

puts( PasswordString.at(Lettere_Scritte).c_str() );
Run Code Online (Sandbox Code Playgroud)

或者您可以使用 C++ iostreams,它知道并且根本std::string不需要调用:c_str()

std::cout << PasswordString.at(Lettere_Scritte);
Run Code Online (Sandbox Code Playgroud)

  • 旁注:你必须小心“printf”。如果你使用 `printf( "%s", PasswordString.at(Lettere_Sritte) );` (注意缺少 `.cstr()`),许多编译器将无法警告你犯了一个错误。警告与否,程序将编译并可能在运行时表现出奇怪的行为。 (2认同)