Hello guys, i'm new here, i want to learn c++. I worked for about 3 hours and i have a problem with scanf, can anyone explain to me?
source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <conio.h>
#include <stdio.h>
usingnamespace std;
int main() {
int a = 5, b = 5;
printf("A value is: %d", a);
printf("\n A value location is: %d \nNew a value is: ", &a);
scanf_s("%d", a);
printf("New number is: %d", a);
return 0;
}
Since this appears to be a C++ program, why are you trying to use the C functions instead of C++ streams?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int main()
{
int a = 5;
std::cout << "A value is: " << a << '\n';
std::cout << "The address of A is: " << &a << '\n';
std::cout << "Please enter a new value for A: ";
std::cin >> a;
std::cout << "The new value of A is: " << a << '\n';
return 0;
}
If you insist on using the error prone C methods then you really should be listening to your compiler, it should be warning you about several mistakes, and you really should find and read the documentation for those standard C functions as well.
scanf_s("%d", &a);
but try not to use scanf, as said above.
you told it to read into memory addres 5, the value of a, not into the memory address of a, where you wanted the data. That is what the error says, but its hard to see that as a beginner, re-read what I said a few times, then re-read the error message, and see if you can connect the problem and message so you can begin to learn the error message reading (it takes practice, but after a while you will see that it tells you everything).
pointers and memory addresses in C take getting used to; c++ avoids the vast majority of those things but you still need a little background in it to read and fix old code and to do a handful of things that require it.
Avoid using the C library as much as possible then, until you have more than a bit of experience writing C++ programs. Learn vectors and C++ strings before looking at arrays and C strings, etc.