2017-04-15 51 views
1

我可以很容易地創建一個void函數來輸出類似標題的東西,但是我不能讓程序讀取用戶的輸入並輸出給他們。如何用void函數讀取名字和姓氏

即。有一個程序說「請輸入您的名字」,然後輸出「您輸入:(他們把什麼)」

什麼,我有一個例子:

#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; 
} 

回答

0

使用cin閱讀,是iostream

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

,如果你希望程序分別顯示姓氏和名字,那麼這樣的:

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

如何是你的答案來自一個不同的張貼@前面21koizyd? –

+0

他或她寫的整個程序,但我想證明薩拉如何獲得第一和最後一個名字聯繫在一起,並分別。我沒有複製@ 21koizyd,如果這是你以爲我發佈在他或她之前的想法。我是新來的所以如果我做錯了,請告訴我我不想提供錯誤的答案或任何東西。 – Tyger

0

試試這個:

#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; 
} 

我想想,你想要這樣的東西。

或用類似「頭」

#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; 
}