我試圖完成一個C++練習,你必須完成一個'Golf'函數的函數定義並設計一個基於此的程序,但是我遇到了其中一個函數的問題。C++中的多重return語句
函數的部分目標是希望在用戶輸入高爾夫球員名稱時返回1,如果沒有輸入名稱,則返回0。
我遇到了一些困難,因爲當我運行該程序時,我總是得到1返回到主。
底下我已經列出了我迄今所做的每個文件:
golf.h
#ifndef GOLF_H
#define GOLF_H
const int Len = 40;
struct golf {
char fullname[Len];
int handicap;
};
void setgolf(golf &g, const char *name, int hc);
int setgolf(golf &g);
void handicap(golf &g, int hc);
void showgolf(const golf &g);
#endif /* GOLF_H */
golf.cpp
#include "golf.h"
#include "iostream"
void setgolf(golf &g, const char *name, int hc) {
strcpy(g.fullname, name);
g.handicap = hc;
}
int setgolf(golf &g) {
std::cout << "Golfer's name:";
std::cin.getline(g.fullname, Len);
if (std::cin.get() == '\0')
return 0;
std::cout << "Golfer's handicap: ";
std::cin >> g.handicap;
return 1;
}
void handicap(golf &g, int hc) {
g.handicap = hc;
std::cout << g.fullname << "'s new handicap is:" << g.handicap;
}
void showgolf(const golf &g) {
std::cout << "Player's Name:" << g.fullname << std::endl;
std::cout << "Player's handicapped:" << g.handicap << std::endl;
}
的main.cpp
#include <cstdlib>
#include <iostream>
#include "golf.h"
using namespace std;
int main(int argc, char** argv) {
int retuVal = 0;
golf ann;
setgolf(ann, "Ann Birdfree", 24);
showgolf(ann);
cout << "\n";
golf peter;
retuVal = setgolf(peter);
cout<<"return value is:"<<retuVal<<endl;
cout << "\nGolf details reset in new handicap\n";
handicap(peter, 5);
cout << "\nDetails reprinted";
showgolf(peter);
return 0;
}
請讓我知道,我做錯了什麼,以便我可以返回0而不是總是返回1。
謝謝Jis。
是的,這是我想要做的 - 如果用戶輸入空字符串返回0。感謝您深入瞭解cin.get()不能做什麼。 – jis