#Python code
user = input("Please enter your name \n")
print ("Your name is,", user)
How can I make this in C++?
#Python code
user = input("Please enter your name \n")
print ("Your name is,", user)
How can I make this in C++?
I don't exactly know what you want to achieve, but I think this is what you're looking for.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string user;
/* ---- This part is in place of your python code --- */
cout << "Please Enter your name"; cin >> user;
cout << "Your name is" << user;
/* --------------------- */
return 0;
}
Unfortunately, the accepted answer does not match the legitimate question, how to realize the input. Consider this solution:
#include <iostream>
#include <string>
template<typename T>
T input(std::string message = "")
{
if (!empty(message)) std::cout << message << " : ";
T value;
std::cin >> value;
return value;
}
int main()
{
auto i = input<int>("integer, followed by decimal point value");
auto d = input<double>();
if (std::cin) std::cout << "Gelesen: " << i << ' ' << d << '\n';
else std::cout << "error reading input";
}
The input()
function does not return a string like in Python, but a value of the type indicated in angle brackets.
To make a function that works as input()
function in python for c++, you can use std::getline()
to get input from the user, and returns it as a std::string
.
#include <iostream>
#include <string>
// Function that works like Python's input() function
std::string input(const std::string& prompt = "") {
std::string user_input;
std::cout << prompt;
std::getline(std::cin, user_input);
return user_input;
}
int main() {
// Usage of input() function
std::string user_input = input("Enter something :");
std::cout << "User Input :" << user_input;
return 0;
}
Using the cast operator template overload for Input()
Using templates and a package of parameters for Print()
#include <iostream>
#include <string>
using namespace std;
struct Input {
Input(string s = "") {
cout << s;
}
template<typename T>
operator T() {
T v; cin >> v;
return v;
}
};
template <typename T> void Print(T t) { std::cout << t << '\n'; }
template<typename T, typename... Args> void Print(T t, Args... args) { std::cout << t << ' '; Print(args...); }
int main() {
int a = Input();
float b = Input("Enter float: ");
char c = Input();
string d = Input("How are you? ");
Print("hello", a, b, c, d);
return 0;
}