Home > front end >  Counting an occurrence of a string in whole program
Counting an occurrence of a string in whole program

Time:04-15

For the context, I'm coding a quiz in C , and I want to count correct answers by counting how many times does a string string yes = "Correct answer" show up during the whole program.

eg.

#include <iostream>
using namespace std;
int main (void)
{
char answer, answer1;
string yes = "Correct";
string no = "Incorrect";

cout<<"1. When was Macintosh II released?"<<endl;
cout<<"a) 1985"<<endl;
cout<<"b) 1989"<<endl;
cout<<"c) 1987"<<endl;
cout<<"Answer: ";
cin>>answer;

if (answer == 'c') cout<<yes<<endl;
else cout<<no<<endl;

cout<<"2. Who created the Linux Kernel?"<<endl;
cout<<"a) Dennis Ritchie"<<endl;
cout<<"b) Linus Torvalds"<<endl;
cout<<"c) Richard Stallman"<<endl;
cout<<"Answer: ";
cin>>answer1;

if (answer1 == 'b') cout<<yes<<endl;
else cout<<no<<endl;



return 0;
}

And now, I want to count how many times does string "yes" show up in the whole program, as that would also count how many questions did the user answer correctly.

I'm new to C and I'm trying to learn. Thanks in advance.

CodePudding user response:

So, if you are learning C is better to start with an object oriented approach. So first of all define an object for the Question object which is able to ask and check the answer, then define a Quiz object which is able to ask all the questions and count the correct answers.

#include <iostream>
#include <vector>

class Question
{
public:
  Question(std::string q, std::string asw) : question(q), answer(asw)
  {
  }

  virtual void Ask()
  {
    std::cout << question << std::endl;
    std::cout << "Answer?" << std::endl;
    std::cin >> user_answer;
  }

  virtual bool Check()
  {
    return user_answer == answer;
  }

private:
  std::string question;
  std::string answer;
  std::string user_answer;
};

class Quiz
{
public:
  Quiz() {}

  void AddQuestion(Question * q)
  {
    questions.push_back(std::shared_ptr<Question>(q));
  }

  int Run()
  {
    int count = 0;
    for (std::shared_ptr<Question> const& q : questions)
    {
        q->Ask();
        count = q->Check() ?   count : count;
    }

    return count;
  }

private:
  std::vector<std::shared_ptr<Question>> questions;
};

int main()
{
  Quiz q;
  q.AddQuestion(new Question("1. When was Macintosh II released ?\na) 1985\nb) 1989\nc) 1987", "a"));
  q.AddQuestion(new Question("2. Who created the Linux Kernel? ?\na) Dennis Ritchie\nb) Linus Torvalds\nc) Richard Stallman", "b"));

  std::cout << "Your score is: " << q.Run() << std::endl;
}

CodePudding user response:

As mentioned in some comments, you can keep a counter, something like this:

int main (void)
{
  int counter_yes = 0;
  void its_correct(){
    counter_yes  ;
    cout<<yes<<endl;
  }
  char answer, answer1;
  string yes = "Correct";
  string no = "Incorrect";
  ...

And you replace every cout<<yes<<endl; by its_correct();.

Have fun.

  • Related