-3

So I have the following code:

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

When the incoming parameter is "03" (the first printf shows 03), I got 0 for month.

However, if I add this line

mon = "03";

I got 3, which is correct, for month.

Why......????

EDIT: I figured it out. You guys were right. DON'T use scanf for string input.

user1447343
  • 1,417
  • 4
  • 18
  • 24

1 Answers1

3

You can't print std::string with %s in printf function, try this:

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;
}

Or

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

But std::cout is preferred over C printf function.

Also don't use scanf with std::string, use std::cin instead of scanf, std::cout instead of printf.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
billz
  • 44,644
  • 9
  • 83
  • 100