【C++學習】【階段一】Essential C++ 第一章習題答案

int askName1() //Exercise1.5-1
{
    char usr_name[200]="";
    cout << "Please write your name : ";
    cin >> usr_name;
    if (strlen(usr_name) < 2)
    {
        cout << "Your input is invalid !Please do it again!";
        askName1();
    }
    else
    {
        cout << "Congratulations!";
    }
    return 0;
}

int askName2() //Exercise1.5-2
{
    string usr_name;
    cout << "Please write your name : ";
    cin >> usr_name;
    if (usr_name.size() < 2)
    {
        askName2();
    }
    else
    {
        cout << "Congratulations!";
    }
    return 0;
}

int getNum() //Exercise1.6
{
    int a[3];
    vector<int> b;
    int x;
    int sumA = 0;
    int sumB = 0;
    int i =0;
    cout << "Please write a number(int) :";
    while (i < 3)
    {
        cin >> x;
        a[i] = x;
        b.push_back(x);
        i++;
    }
    for(int i =0 ; i<3; i++)
    {
        sumA += a[i];
        sumB += b[i];
    }
    int a_len = sizeof(a) / sizeof(a[0]);
    float averageA = float(sumA / a_len);
    float averageB = float(sumB/b.size());
    cout << "SumA : "<< sumA << " AverageA : "<< averageA << '\n';
    cout << "SumB : "<<sumB << "AverageB : "<< averageB;
    return 0;
}

int getText() //Exercise1.7
{
    vector<string> words;
    ifstream infile("D:/test.txt",ios_base::in);
    if(!infile)
    {
        //
    }
    else
    {
        string data;
        while(infile >> data)
        {
            words.push_back(data);
        };
        sort(words.begin(),words.end());
        for(int i =0;i<words.size();i++)
        {
            cout << words[i] << ' ';
        };
    }
    ofstream outfile("D:/output.txt",ios_base::app);
    if(!outfile)
    {
        //
    }
    else
    {
        for(int i =0;i<words.size();i++)
        {
            outfile << words[i] << ' ';
        }

    }
    return 0;
}

int switchFunc() //Exercise1.8
{
    int num_tries;
    string message[4] = {
        "Oops! Nice guess but not quite it.\n",
        "Hmm. Sorry. Wrong again.\n",
        "Ah, this is harder than it looks, isn't it?\n",
        "It must be getting pretty frustrating by now!\n"
    };
    cin >> num_tries;
    switch(num_tries)
    {
    case 1:
    case 2:
    case 3:
        cout << message[num_tries-1];
        break;
    default:
        cout << message[3];
        break;
    };

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章