C ++添加数组

如何解决C ++添加数组

我是C ++的新手,目前已参加入门课程。我正在创建的程序是编程教程(具有讽刺意味的!),当前正在尝试添加菜单选项,该菜单选项会将用户带到测验中。没有什么花哨。截至目前,似乎我的函数无法识别我创建的类。到目前为止,这就是我的建议,我们将不胜感激任何精打细算的建议!

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
    string username = "";
    int choice;
    char c;
    char answer;
    int x = 4;
    int y = 5;
    int z = x + y;
    int ans;
    int total;
    
    class Question
    {
    private:
        string Question_Text;
        string Answer_one;
        string Answer_two;
        string Answer_three;

        int Correct_Answer;
        int Question_Score;

    public:
        void setValues(string,string,int,int);
        void askQuestion ( );
    };

    //welcome message
    cout << "Hello user,please enter your name:";
    cin >> username;
    cout << "Welcome to the programming tutorial " << username << "."<< endl;

    //menu selection
    while(toupper (choice != 'E'))
    {
        cout << "What would you like to do? (Unit 1 - Declaring Variables (1),Unit 2 - Input/ Output (2),Unit 3 - Conditionals (3),Quizzes (4) or Exit (E))";
        cin >> choice;
        if (choice == '1')
        {
            cout << "We will begin with defining variables. The first step to doing this is choosing which datatype your variable is.\n";
            cout << "The following are a few of the common datatypes used in programming.\n";
            cout << "Character ==> char\n";
            cout << "Integer ==> int,long,double\n";
            cout << "Boolean ==> bool\n";
            cout << endl;
            cout << "When declaring a variable,you must put its datatype before the variable name.\n";
            cout << "An example of this would be if we wanted to declare the value of x as 4.\n";
            cout << "We would write this as: \n";
            cout << "int x = 4\n";
            cout << "The program will now use the value 4 for the variable name 'x'\n";
            cout << endl;
            cout << "Now let's assume we assigned the value of 5 to the variable 'y'\n";
            cout << "If we wanted to add x and y and assign the sum to the variable 'z',we would write:\n";
            cout << "int z = x + y\n";
            cout << "Now when we use the variable 'z' in our program,it will perform the calculation given x=4 and y=5 and declare 9 as the value of the variable 'z'.\n";
            cout << "To test our code,we would write: " << endl;
            cout << "cout<<'x + y'<< z << endl; \n";
            cout << "If written correctly,it will display as: \n";
            cout << "x + y = " << z << "." << endl;
            
        }
        if (choice == '2')
        {
            cout << "Now that we understand the basics of declaring variables,let's discuss displaying,or output of,information to a user.\n";
            cout << "If you wanted to display a welcome message,for example,you would type:\n";
            cout << "cout << 'Welcome';\n";
            cout << "The line of code would start with 'cout' followed by two less than signs and then the message you wish to display in quotes.\n";
            cout << "Using this,you can ask the user for input.\n";
            cout << "Enter c to continue...";
            cin >> c;
            cout << "Let's say we have a program that flips a coin. You may want to ask the user how many times to flip the coin.\n";
            cout << "Assuming we previously declared this amount variable as 'int timesFlipped',we would 'cout' our question and the next line would read:\n";
            cout << "cin>> timesFlipped; \n";
            cout << "This will store the users input for the variable 'timesFlipped'\n";
            cout << "You almost always end a line of code with a semi colon."<<endl;
        }
        if (choice == '3')
        {
            cout << "This unit will cover conditional expressions."<<endl;
        }
        if (choice == '4')
        {
            string Question_Text;
            string Answer_one;
            string Answer_two;
            string Answer_three;

            int Correct_Answer;
            int Question_Score;
            Question q1;
            Question q2;
            Question q3;
        
            
            cout <<username << ",you have chosen to take a quiz." << endl << endl;
            int ans,score = 0;
            cout << "Unit One Quiz - Variables " << endl << endl;

            q1.setValues("How would you declare the value of 'x' as 12? ","x=12()","x==12()","x=12;()",3,1);
            q2.setValues("What do you need to put before a variable when declaring it?","a name()","a value()","a datatype()",1);
            q3.setValues("Which data type would you use for a number that includes a decimal value?","int()","double()","float()",2,1);

            q1.askQuestion();
            q2.askQuestion();
            q3.askQuestion();
            
            cout << "Your score out of a possible 3 is " << total << endl;

        }
        if (choice == 'E')
        {
            cout << "Have a good day!";
            break;
        }
    }


    system("pause");
}

void Question :: setValues(string q,string a1,string a2,string a3,int ca,int pa)
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;
    
    Question_Text = q;
    Answer_one = a1;
    Answer_two = a2;
    Answer_three = a3;
    Correct_Answer = ca;
    Question_Score = pa;
}

void Question :: askQuestion()
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;
    int ans;
    int Total;

    cout << endl;
    cout << Question_Text << endl;
    cout << "1. " << Answer_one << endl;
    cout << "2. " << Answer_two << endl;
    cout << "3. " << Answer_three << endl << endl;
    cout << "Please enter your answer: " << endl;
    cin >> ans;

    if (ans == Correct_Answer)
    {
        cout << "That is correct!" << endl;
        Total = Total + Question_Score;
    }
    else
    {
        cout << "Sorry,that is incorrect" << endl;
        cout << "The correct answer was " << Correct_Answer << endl;
    }
}

我在这两个函数中都声明了变量,因为直到我这样做时才在每个函数中都识别出它们,但是现在我在想这是因为无法识别该类。 >

解决方法

针对您遇到的问题,您的程序可以简化为以下内容:

int main() 
{
    class Question  {
    public:
        void askQuestion();
    };

    Question q;
    q.askQuestion();
}

void Question::askQuestion() { }

Question::askQuestion()的定义中会出现错误,因为该类是在main()函数的范围内声明(并定义)的-在它的外部无法识别。

将班级移到main()之外,就像这样:

class Question  {
public:
    void askQuestion();
};

int main() 
{
    // you can use the Question class here,even though you haven't
    // defined all of its methods yet!
    Question q;
    q.askQuestion();
}

void Question::askQuestion() { }

...,并且此程序执行compile(godbolt.org)。

这还不是全部,但是...您要在每个成员函数中声明成员变量(例如Question_text)。本地定义掩盖了类成员,因此您只需设置方法的本地变量,该变量在执行完成时会被破坏。


其他注意事项和建议:

  • 如果类已经有了方法名称,则无需在方法名称中再次使用单词Question。即Question::ask()Question::askQuestion()似乎是更好的名称选择。 Question::Question_text也是如此。
  • 最好使用avoid using namespace std,并且仅使用您专门打算引用的std::中的类,类型或函数。
  • 如果考虑一下,对Question类的使用是相当人为的。它的代码主要是用于进行测验的代码,而不是诸如此类的问题。似乎最好选择“对象”是一组答案和值或问题参数。可以通过构造QuestionParameters对象来设置值,并提出问题可能是采用此类对象的函数。
  • 如果您有Answer_oneAnswer_twoAnswer_three-那么您可能需要一个容器,例如std::vector<std::string> answers。然后,您可以使用答案索引而不是使用ifswitch语句。
,

在主函数之外定义类时必须进行的更改 使用开关代替if 使用int值而不是E退出程序。 我对代码进行了如下更改

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class Question
{
private:
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;

public:
    void setValues(string,string,int,int);
    void askQuestion();
}; //end of class

//---------------------------
void Question ::askQuestion()
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;
    int ans;
    int Total;

    cout << endl;
    cout << Question_Text << endl;
    cout << "1. " << Answer_one << endl;
    cout << "2. " << Answer_two << endl;
    cout << "3. " << Answer_three << endl
         << endl;
    cout << "Please enter your answer: " << endl;
    cin >> ans;

    if (ans == Correct_Answer)
    {
        cout << "That is correct!" << endl;
        Total = Total + Question_Score;
    }
    else
    {
        cout << "Sorry,that is incorrect" << endl;
        cout << "The correct answer was " << Correct_Answer << endl;
    }
} //end of askQuestion
//----------------------------------
void Question ::setValues(string q,string a1,string a2,string a3,int ca,int pa)
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;

    Question_Text = q;
    Answer_one = a1;
    Answer_two = a2;
    Answer_three = a3;
    Correct_Answer = ca;
    Question_Score = pa;
} //end of setValues
//----------------------------------

int main()
{
    string username = "";
    int choice;
    char c;
    char answer;
    int x = 4;
    int y = 5;
    int z = x + y;
    int ans;
    int total;

    //welcome message
    cout << "Hello user,please enter your name:";
    cin >> username;
    cout << "Welcome to the programming tutorial " << username << "." << endl;

    //menu selection

    while (choice != 5)
    {
        cout << "What would you like to do? (Unit 1 - Declaring Variables (1),Unit 2 - Input/ Output (2),Unit 3 - Conditionals (3),Quizzes (4) or Exit (5))";
        cin >> choice;

        switch (choice)
        {
        case 1:
        {
            cout << "We will begin with defining variables. The first step to doing this is choosing which datatype your variable is.\n";
            cout << "The following are a few of the common datatypes used in programming.\n";
            cout << "Character ==> char\n";
            cout << "Integer ==> int,long,double\n";
            cout << "Boolean ==> bool\n";
            cout << endl;
            cout << "When declaring a variable,you must put its datatype before the variable name.\n";
            cout << "An example of this would be if we wanted to declare the value of x as 4.\n";
            cout << "We would write this as: \n";
            cout << "int x = 4\n";
            cout << "The program will now use the value 4 for the variable name 'x'\n";
            cout << endl;
            cout << "Now let's assume we assigned the value of 5 to the variable 'y'\n";
            cout << "If we wanted to add x and y and assign the sum to the variable 'z',we would write:\n";
            cout << "int z = x + y\n";
            cout << "Now when we use the variable 'z' in our program,it will perform the calculation given x=4 and y=5 and declare 9 as the value of the variable 'z'.\n";
            cout << "To test our code,we would write: " << endl;
            cout << "cout<<'x + y'<< z << endl; \n";
            cout << "If written correctly,it will display as: \n";
            cout << "x + y = " << z << "." << endl;
            break;
        }

        case 2:
        {
            cout << "Now that we understand the basics of declaring variables,let's discuss displaying,or output of,information to a user.\n";
            cout << "If you wanted to display a welcome message,for example,you would type:\n";
            cout << "cout << 'Welcome';\n";
            cout << "The line of code would start with 'cout' followed by two less than signs and then the message you wish to display in quotes.\n";
            cout << "Using this,you can ask the user for input.\n";
            cout << "Enter c to continue...";
            cin >> c;
            cout << "Let's say we have a program that flips a coin. You may want to ask the user how many times to flip the coin.\n";
            cout << "Assuming we previously declared this amount variable as 'int timesFlipped',we would 'cout' our question and the next line would read:\n";
            cout << "cin>> timesFlipped; \n";
            cout << "This will store the users input for the variable 'timesFlipped'\n";
            cout << "You almost always end a line of code with a semi colon." << endl;
            break;
        }
        case 3:
            cout << "This unit will cover conditional expressions." << endl;
            break;
        case 4:
        {
            string Question_Text;
            string Answer_one;
            string Answer_two;
            string Answer_three;

            int Correct_Answer;
            int Question_Score;
            Question q1;
            Question q2;
            Question q3;

            cout << username << ",you have chosen to take a quiz." << endl
                 << endl;
            int ans,score = 0;
            cout << "Unit One Quiz - Variables " << endl
                 << endl;

            q1.setValues("How would you declare the value of 'x' as 12? ","x=12()","x==12()","x=12;()",3,1);
            q2.setValues("What do you need to put before a variable when declaring it?","a name()","a value()","a datatype()",1);
            q3.setValues("Which data type would you use for a number that includes a decimal value?","int()","double()","float()",2,1);

            q1.askQuestion();
            q2.askQuestion();
            q3.askQuestion();
            cout << "Your score out of a possible 3 is " << total << endl;
            break;
        }

        case 5:
            cout << "Have a good day!";
            break;
        } //end of switch
    } //end of while

    system("pause");

    return 0;
} //end of main

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res