Scanf is being prioritized over printf ?

Joined
Nov 5, 2023
Messages
1
Reaction score
1
I am beginner in C so I don´t really see my fault here but my programm just skips all printf and starts with the scanf. What did I do wrong? I replaced scanf with fgets but the same thing happens.
Here´s my code:

#include <iostream>
using namespace std;

int main() {


printf("What is your name? \n");
char name[20] ;
printf("My name is: \n");
fgets(name, 20 , stdin);
printf("Your name is %s", name);



return 0;
}
 
Joined
Jul 4, 2023
Messages
366
Reaction score
41
C version
[ working code on-line ]
C:
#include <stdio.h>

int main() {
    printf("What is your name? \n");
    char name[20];
    printf("My name is: \n");
    scanf("%20s", name);
    printf("Your name is %s", name);

    return 0;
}

C++ version
[ working code on-line ]
C++:
#include <iostream>
#include <string>

int main() {
    std::cout << "What is your name? " << std::endl;
    std::string name;
    std::cout << "My name is: " << std::endl;
    std::cin >> name;
    std::cout << "Your name is " << name << std::endl;

    return 0;
}

or
[ working code on-line ]
C++:
#include <iostream>
#include <string>

using namespace std;

int main() {
    cout << "What is your name? " << endl;
    string name;
    cout << "My name is: " << endl;
    cin >> name;
    cout << "Your name is " << name << endl;

    return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top