C++的阿托伊是如何工作的?

How Does C++'s atoi work?

本文关键字:工作 何工作 C++      更新时间:2023-10-16

所以我有以下代码:

void Start(int &year, string &mon, char &nyd)
{
    printf("%s", mon);
    int month= atoi(mon.c_str());
    printf("%i", month);
}

当传入参数为"03"(第一个 printf 显示 03)时,我得到 0 表示月份。

但是,如果我添加此行

mon = "03";

我得到了 3 个月,这是正确的。

为什么。。。。。。????

编辑:我想通了。你们是对的。不要使用 scanf 进行字符串输入。

你不能在printf函数中打印带有%s的std::string,试试这个:

void Start(int &year, const std::string &mon, char &nyd)
{
    std::cout << mon << std::endl;
    int month= atoi(mon.c_str());
    std::cout << month << std::endl;
}

void Start(int &year, string &mon, char &nyd)
{
    printf("%sn", mon.c_str());
    int month= atoi(mon.c_str());
    printf("%in", month);
}

但是 std::cout 优于 C printf 函数。

也不要使用 scanf 和 std::string,使用 std::

cin 而不是 scanf,std::cout 而不是 printf。