2017-07-15 79 views
-6

我试图让我的代码返回,在这种情况下,星期一或星期二,这取决于输入。在电话键盘上,星期一的数字是666329,星期二的数字是8837329.所以如果星期一的数字被读取,那么应该将星期一输出到屏幕,反之亦然。我怎样才能让代码使用if语句中提供的数字返回星期几。使用字符进行动态分配

#include<iostream> 

using namespace std; 

void setKey(char *keyPress); 

int main() 
{ 
    char *keyPress; 

    keyPress = new char[10]; 

    setKey(keyPress); 

    system("pause"); 
    return 0; 
} 

void setKey(char *keyPress) 
{ 
    cout << "Enter the day using the number keypad: "<< endl << endl; 
    cin >> keyPress; 
    cout << endl << endl; 

    if (keyPress == "666329") 
     cout << "Monday" << endl << endl; 
    else if (keyPress == "8837329") 
     cout << "Tuesday" << endl << endl; 
} 
+1

此代码不会编译,请在询问之前显示您的实际代码。注意:你不能以这种方式比较C字符串。 –

+1

你的问题是什么?你也应该首先阅读一本好的C++书,这段代码有很多问题 – UnholySheep

+0

你包含'',所以使用'std :: string'。如果你使用它,也不需要“新”任何东西。 – StoryTeller

回答

1

是否有任何特定原因不使用std::string? 一种解决方案,使用std::string是:

#include<iostream> 

using namespace std; 

void setKey(string& keyPress); 

int main() 
{ 
    string keyPress; 
    setKey(keyPress); 
    //rest here 
} 

void setKey(string& keyPress) 
{ 
    cout << "Enter the day using the number keypad: "<< endl << endl; 
    cin >> keyPress; 
    cout << endl << endl; 

    if (keyPress == "666329") 
     cout << "Monday" << endl << endl; 
    else if (keyPress == "8837329") 
     cout << "Tuesday" << endl << endl; 
} 

如果你还是想用c-style字符串,你需要将它们用下面的函数比较: strcmp

而且,你有内存泄漏你的码。您正在使用new而没有delete