使用char进行动态分配

时间:2017-07-15 11:06:53

标签: c++

我想让我的代码返回,在这种情况下,周一或周二,具体取决于输入。在电话键盘上,星期一的数字是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 个答案:

答案 0 :(得分:1)

有没有具体的理由不使用trace? 使用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; } 字符串,则需要将它们与以下函数进行比较: strcmp

此外,您的代码中存在内存泄漏。您使用的c-style没有new