Why is my code not returning 0? I'm using scanf() instead of cin

0

I wanted to make sure I understood how to use scanf(), but I don't understand why my code didn't return 0. I understand that scanf() has it's own issue when it comes to loops, etc, but it bewilders me how something as simple as displaying a string wouldn't return 0.

Is there perhaps any problems with my code?

My simple code to type and display a name is as follows:

#include <iostream>
using namespace std;

int main() {
  string name[15];
  printf("Please type your name: ");
  scanf("%s", &name);
  printf("Your name is %s", name);
  return 0;
}

The output would be:

Your name is hello
Process returned -1073740940 (0xC0000374)   execution time : 4.356 s
Press any key to continue.

while if I use cin/cout instead of scanf()/printf(),

#include <iostream>
using namespace std;

int main(){
    string name;
    cout << "Please type your name: ";
    cin >> name;
    cout << "Your name is: " << name;
    return 0;
}

Output:

Please type your name: hello
Your name is: hello
Process returned 0 (0x0)   execution time : 3.794 s
Press any key to continue.
c++
scanf
asked on Stack Overflow May 19, 2020 by xhar12345 • edited May 19, 2020 by walnut

1 Answer

2

Your first program has undefined behavior.

scanf and printf expect for the %s a pointer to char, not a pointer to std::string. They are C library functions and as such don't know anything about C++ types such as std::string. You are required to provide the correct type as argument for the format specifier. If you don't, your program has undefined behavior.

So, in the first code block, you need to replace

string name[15];

with

char name[15];

Note that this is still unsafe, because you will access the array out-of-bounds if the user inputs a string longer than 14 characters, again causing undefined behavior with that input.

Also, enable warnings in your compiler, e.g. with the compiler flags

-Wall -Wextra

in GCC and Clang. It is likely that the compiler will then warn you about the wrong argument type.

In addition, replace #include<iostream> by #include<cstdio> in the first program. scanf and printf are provided by the standard library header <cstdio>. <iostream> is not guaranteed to include them. Similarly the second program requires an additional #include<string>, because <iostream> is also not guaranteed to provide std::string.

answered on Stack Overflow May 19, 2020 by walnut • edited May 19, 2020 by walnut

User contributions licensed under CC BY-SA 3.0