-3

For instance if in this code i don't use getchar(), a compilation error shwos up. Please explain the reason?

    #include <iostream>
 #include <iomanip>
 #include <limits>
 
 using namespace std;
 
 int main() {
     int i = 4;
     double d = 4.0;
     string s = "HackerRank ";
     int a;
     double b;
     char c[50];
     cin>>a;
     cin>>b;
     getchar();
     gets(c);
     cout<<a+i<<"\n";
     cout<<setprecision(1)<<fixed<<d+b<<"\n";
     cout<<s+c;
     return 0; }
  • 3
    What error shows up? Please copy and paste the exact error into your post. (And [`gets()` should be avoided](https://stackoverflow.com/q/1694036/1270789).) – Ken Y-N Jul 03 '20 at 02:48
  • 1
    have you tried to include also for visual studio you should use gets_s not gets – Paul Baxter Jul 03 '20 at 02:51
  • Are you saying that this code currently compiles and that when you comment out `getchar();`, a new compiler error occurs when compiling? – chris Jul 03 '20 at 03:11
  • This compiles under visual studio with no warnings or errors. change gets to gets_s and use .c_str when printing strings – Paul Baxter Jul 03 '20 at 03:13
  • 1
    There's a lot of mention of `gets_s`, but you should probably be reaching for `std::getline` by default. It's easier to use and safer, but slower (which doesn't matter for input in most cases). – chris Jul 03 '20 at 03:25
  • Did you take time to read some [documentation about C++](https://en.cppreference.com/w/cpp) and some good [C++ programming book](https://stroustrup.com/programming.html) ? Did you read the documentation of your compiler? Try [GCC](http://gcc.gnu.org/)... Or of your debugger? Try [GDB](https://www.gnu.org/software/gdb/) – Basile Starynkevitch Jul 03 '20 at 03:25
  • 3
    @chris indeed, furthermore, mixing `std::cin` and `getchar()`/`gets()` is asking for trouble. – Ken Y-N Jul 03 '20 at 03:27
  • @KenY-N, `sync_with_stdio` is on by default, so that should work as intended at least. – chris Jul 03 '20 at 03:29

1 Answers1

2

this works on my machine.

#include <iostream>
#include <iomanip>
#include <limits>
#include <cstdio>

using namespace std;

int main()
{
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";
    int a;
    double b;
    char c[50];
    cin >> a;
    cin >> b;
    getchar();
    gets_s(c);
    cout << a + i << "\n";
    cout << setprecision(1) << fixed << d + b << "\n";
    cout << (s + c).c_str();
    return 0;
}
Paul Baxter
  • 1,054
  • 12
  • 22