2014-03-12 70 views
0

我們的教授告訴我們要創建一個函數,如果用戶在年齡上輸入字母,它會讓用戶再次重新輸入年齡。但是,只有年齡纔會更新,不需要再次輸入姓名, 我試過了,但這裏是我的代碼。如果用戶輸入一個字母作爲輸入,重新輸入年齡

#include <iostream> 
#include <fstream> 
#include <cstdlib> 

using namespace std; 
string inputName, inputGender, inputBirthday; 
int inputAge, inputChoice; 
ofstream fileOutput("Example.txt"); 
int getAge() { 
    cin>>inputAge; 
    if (inputAge <= 50) { 
     fileOutput<<inputAge<<endl; 
    } else { 
     cout<<"Error: Re-enter your age: "; 
     cin>>inputChoice; 
     getAge(); 
    } 
} 

int main() { 
    cout<<"Enter your Name:  "; 
    getline(cin, inputName); 
    fileOutput<<inputName<<endl; 
    cout<<"Enter your Age:  "; 
    getAge(); 
    cout<<"Enter your Gender: "; 
    getline(cin, inputGender); 
    fileOutput<<inputGender<<endl; 
    cout<<"Enter your Birthday: "; 
    getline(cin, inputBirthday); 
    fileOutput<<inputBirthday<<endl; 
    fileOutput.close(); 
    cout<<"Done!\n"; 
    system("PAUSE"); 
    return 0; 
} 
+2

使用while循環。 – Brian

+0

但我該怎麼做呢?謝謝:) – user3288922

回答

1

除非你要返回一個int,存在與int回報

void getAge() 
{ 
    std::string line; 
    int i; 
    while (std::getline(std::cin, line)) 
    { 
     std::stringstream ss(line); 
     if (ss >> i) 
     { 
      if (ss.eof()) 
      { 
       break; 
      } 
     } 
     std::cout << "Please re-enter the age as an integer" << std::endl; 
    } 
    if (i <= 50) 
    { 
     fileOutput << i <<endl; 
    } 
} 
+0

它說「變量std :: stringstream ss'有初始化,但不完整的類型」 – user3288922

+0

@ user3288922:你有包括字符串?例如'#include '? – Brian

+0

是的,我已經包含了字符串庫 – user3288922

0

獲得一個數量,同時扔掉壞輸入聲明getAge沒有點更麻煩比我的喜歡。這裏有一個通用的方法:

template <typename T> 
T get_on_line(std::istream& is, const std::string& retry_msg) 
{ 
    std::string line; 
    while (std::getline(std::cin, line)) 
    { 
     std::istringstream iss(line); 
     T x; 
     char c; 
     if (iss >> x) 
      if (iss >> c) 
       throw std::runtime_error("unexpected trailing garbage on line"); 
      else 
       return x; 
     else 
      std::cerr << retry_msg << '\n'; 
    } 
} 

用法:

int num = get_on_line<int>(std::cin, "unable to parse age from line, please type it again"); 
相關問題