2014-01-24 77 views
0

我試着用盡可能多的方式重新定義這些變量 試圖讓這一行起作用。在這裏我只舉一個例子 來表示困擾我的事情。使用if語句的C++字符串變量

double const FRAME_COST = 45.00; 
string input; 
char yes, 
    no; 
int frames; 


cout << "Do you want additional frames? Type yes/no: "; 
cin >> input; 

    if (input == yes){ 
     cout << "How many?" 
     cin >> frames; 
     frames = frames * FRAME_COST; 
     } 

// The problem is in **the if statement** 
// I need to use a string not a bool (according to my professor) 
// I can't get the compiler to recognize the **if statement** 
// I realize this isn't practical, but he always throws curve balls. 

回答

7

您當前的方案已未定義行爲,因爲yesno是尚未初始化字符變量,並且使用的是其中的一個比較。

要修復,去除yesno聲明(你不需要它們),並使用字符串文字來代替:

if (input == "yes") { 
    ... 
} 

注意:您比較可能過於嚴格,因爲它是區分敏感。這將需要yes,但它不會採取YesYES作爲答案。要解決這個問題,您可能希望在比較之前將輸入字符串轉換爲小寫。

+0

謝謝。我現在知道了。 – judonomi

3

只要有一個名爲「是」 char和另一名char「不」是不夠的,尤其是你從來沒有真正給他們任何價值。我覺得你的意思寫:

if (input == "yes") { 
2

你需要做一個字符串或字符數組的比較。

if (input == yes) 

這一行什麼也不做的yes是從未初始化字符指針。它應該是

if (input == "yes") 

而且你不需要yes變量(或者,你可以聲明常數字符串值進行檢查:如const std::string YES("yes");

注意,你應該也佔病例靈敏度。

此外,你乘以一個整數frames一個雙重FRAME_COST(大概是爲了得到總成本?)。這會導致一個截斷的整數值,因爲您將它存儲在int中。如果你想在費用爲美元和美分,你應該把它存放在doublefloat

double cost = frames * FRAME_COST; 
1

yesno應該是字符串常量(如果你想使他們完美匹配與輸入),要麼const std::string要麼const char*(或自動),但你必須assigh一個值。

double const** FRAME_COST = 45.00; 
string input; 
const char* yes = "yes" 
const char* no = "no"; 
int frames; 


cout << "Do you want additional frames? Type yes/no: "; 
cin >> input; 

    if (input == yes){ // exact comparison (maybe add a space trim of input?) 
     cout << "How many?" 
     cin >> frames; 
     frames = frames * FRAME_COST; 
     } 
3

input == yes必須input == "yes"引號讓編譯器知道這是一個字符串,而不是一個標識符。我也認爲this可能會有所幫助。

3
const string YES = "yes"; 
const string NO = "no"; 
const double FRAME_COST = 45.0; 


int main() 
{ 
    string input; 
    double frames; 
    cout << "Hello World" << endl; 
    cin >> input; 

    if(input == YES) 
    { 
     cout << "How many?" << endl; 
     cin >> frames; 
     frames = frames * FRAME_COST; 
     cout << frames << endl; 
    } 

    return 0; 
}