簡體   English   中英

C++ Q1.8 必備的煩惱

[英]Trouble of essential c++ Q1.8

我正在通過閱讀 C++ 來學習 C++。 但是程序在expected a ","被中斷expected a ","

#include <iostream>
#include <string>


using namespace std;


int main()
{
    const char* msg_to_usr(int num_tries)
    {
        const int rsp_cnt = 5;
        static const char* usr_msgs( rsp_cnt ) = {
            "Go on,male a guess.",
            "Oops! Nice quess but not quite it.",
            "Hmm.Sorry Wrong again",
            "Ah, this is harder than it looks,no?",
            "It must be getting pretty frustrating by now!"
        };
        if (num_tries < 0)
            num_tries = 0;
        else
        if (num_tries >= rsp_cnt)
            num_tries = rsp_cnt - 1;
        return usr_msgs(num_tries);
        
    }
    
}

有人能幫我擺脫這種困惑嗎?

幾點:

  1. 那本書中沒有任何地方嘗試main()定義該函數,這會給您帶來問題。 事實上,它只是向你展示了函數本身,沒有任何可以讓你運行它的東西,讓你添加它(事實證明是錯誤的)。 包含完整程序的書籍通常更好,因為它們不會讓初學者犯那種特定的錯誤。

  2. 您在書中的[]的幾個地方使用() (使用usr_msgs ),將數組訪問轉換為無效的函數定義和調用。 下面的代碼將是進一步探索的良好起點(解決了這兩個問題):

#include <iostream>
using namespace std;

const char *msg_to_usr(int num_tries) {
    const int rsp_cnt = 5;
    static const char *usr_msgs[rsp_cnt] = {
        "Go on,male a guess.",
        "Oops! Nice quess but not quite it.",
        "Hmm.Sorry Wrong again",
        "Ah, this is harder than it looks,no?",
        "It must be getting pretty frustrating by now!"
    };
    if (num_tries < 0)
        num_tries = 0;
    else if (num_tries >= rsp_cnt)
        num_tries = rsp_cnt - 1;
    return usr_msgs[num_tries];
}

int main() {
    // Test harness.
    for (int tries = 0; tries < 10; ++tries)
        cout << msg_to_usr(tries) << '\n';
}

為了完整起見,這里是書中整個片段的圖像,並指示您的代碼偏離的位置: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM