2013-10-29 37 views
0

每次在此函數中輸入類型都有錯誤時,它會自動將* _cost的值設置爲0.爲什麼會發生這種情況?使用getline和cin指定用戶輸入

void Item::setCost(string input){ 
float entered; 
istringstream stin; 
stin.str(input); 
if(!(stin >> entered)){ 
    do{ 
     cout << "invalid input" << endl; 
     stin.clear(); 
     getline(cin, input); 
     stin.str(input); 
     *_cost = entered; 
    } 
    while(!(stin >> entered)); 
} 
else{ 
    *_cost = entered; 
} 
} 

我使用的功能在我的主要功能如下:

istringstream stin; 
string input; 

cout << "enter cost" << endl; 
getline(cin, input); 
items[i]->setCost(input); 
+0

_'我是一個新的C++程序員。'_這個病,只是浪費帶寬!我們通過查看你的問題來了解我(我今天真的很**脾氣暴躁,因爲我喜歡浪費帶寬)...... –

回答

1

您正在將*_cost設置爲一個值,因爲if語句,它始終是一個必然不正確的值。
*_cost = entered行只有在程序正在通過其「無效輸入」代碼時纔會執行。程序只在輸入時打印「無效輸入」不是合法值。因此_cost只能設置爲非法值。
要解決您的問題,請在do-while循環之後放置*_cost = entered

我不知道你爲什麼不直接使用std :: cin直接讀取數據,而不是將標準輸入轉換爲std :: string的實例,然後轉換爲istringstream。

0

在執行代碼中的*_cost = entered;entered是無效的。

我剛纔跟你的初衷修正你的代碼

bool Item::setCost(string input) { 
    bool ret_val = true; 
    float entered = 0.0; 
    istringstream stin; 
    stin.str(input); 

    while (!(stin >> entered)) { // loop till you read a valid input 
     if (!stin.rdbuf()->in_avail()) { 
      ret_val = false; 
      break; 
     } 
    } 

    *_cost = entered; 
    return ret_val; 
} 

stin.rdbuf()->in_avail()可以用來獲取可用字符準備從一個字符串流讀取計,你可以用它來檢查,如果你的stringstream是空的。」

例如,如果你想從istringstream中提取一個float,但你得到了其他的東西(失敗條件),然後看看是否有任何遺留字符(即數字),你可以檢查是否stin.rdbuf()->in_avail() == 0

1

您需要將*_cost = entered中的第一個移出do .. while塊,成爲其後的第一個語句。完成之後,您會看到進一步的重構,雖然不是必需的。

while(!(stin >> entered)) 
{ 
    cout << "invalid input" << endl; 
    stin.clear(); 
    getline(cin, input); 
    stin.str(input); 
} 
*_cost = entered;