简体   繁体   中英

How to read first and last name with void function

I can easily create a void function to output something like a header, but I cannot get a program to read a user's input and then output it to them.

ie. Have a program say "Please enter your first name" and then output "You entered: (what they put)"

An example of what I have:

#include<iostream>
#include<conio.h>
#include<iomanip>
#include<fstream>

using namespace std;

void namefn()//namefn prototype

int main(){
    string firstName,lastName;
    return 0;
}

void namefn(string firstName, string lastName){
    cout<<"please enter your first and last name "<<endl;
}

Use cin to read, is in iostream .

ie

cin >> firstName;
cout << "enter your first and last name:";
cin >> firstName >> lastName;
cout << firstName << " " << lastName;

if you want the program to display the first name and last name separately then this:

cout << "enter you first name:";
cin >> firstName;
cout << firstName << endl;
cout << "Enter your last name:";
cin >> lastName;
cout << lastName << endl;

Try this:

#include <iostream>
#include <string>

void displayFirstAndLast(const std::string& firstName, const std::string& lastName)
{
     std::cout << "You are " << firstName << " " << lastName << std::endl;
}


int main(){
     std::string firstName;
     std::string lastName;
     std::cout << "Please enter your first and last name " << std::endl;
     std::cin >> firstName >> lastName;
     displayFirstAndLast(firstName, lastName);
     return 0;
}

I think, that you want something like this.

Or with something like "header"

#include <iostream>
#include <string>

void displayFirstAndLast(const std::string& firstName, const std::string& lastName);

int main(){
     std::string firstName;
     std::string lastName;
     std::cout << "Please enter your first and last name " << std::endl;
     std::cin >> firstName >> lastName;
     displayFirstAndLast(firstName, lastName);
     return 0;
}

void displayFirstAndLast(const std::string& firstName, const std::string& lastName)
{
     std::cout << "You are " << firstName << " " << lastName << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM