Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ --- error C2664: 'int scanf(const char *,...)' : cannot convert argument 1 from 'int' to 'const char *'

Tags:

c++

scanf

I'm very new to C++ and I'm trying to build this very simple code, but I don't understand why I get this error:

Error   1   error C2664: 'int scanf(const char *,...)' : cannot convert argument 1 from 'int' to 'const char *'

Here is the code:

// lab.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h> 

int main(int argc, char* argv[])
{
    int row = 0;
    printf("Please enter the number of rows: ");
    scanf('%d', &row);
    printf("here is why you have entered %d", row);
    return 0;
}
like image 251
0xtuytuy Avatar asked Mar 16 '23 22:03

0xtuytuy


2 Answers

Change scanf('%d', &row); to

scanf("%d", &row);

'%d' is a multicharacter literal which is of type int.

"%d" on the other hand is a string literal, which is compatible with the const char * as expected by scanf first argument.

If you pass single quoted %d, compiler would try to do an implicit conversion from int(type of '%d') to const char * (as expected by scanf) and will fail as no such conversion exist.

like image 121
Mohit Jain Avatar answered Apr 08 '23 10:04

Mohit Jain


Hope you understood your error by now.And you have done this code in C and not in C++.You need to include the header iostream ...

#include<iostream>
using namespace std;

    int main()
    {
        int row = 0;
        cout<<"Please enter the number of rows: ";
        cin>>row;
        cout<<"entered value"<<row;

    }

Hope this helps..!

like image 32
puja Avatar answered Apr 08 '23 10:04

puja