Question

I have this code:

#include <iostream>
#include <string>
#include "header8.h"

using namespace std;

int main()
{
    Counter test;
    string input;

    cout << "Enter a string\n";
    getline(cin, input);
    test.countcharacters();
    test.countnumbers();
}

void Counter::countcharacters(){
    for(unsigned int i=0; i<input.length(); i++){
        if(input.at(i) == 'a'){
            alphabet[0]++;
        }
    }
}

void Counter::countnumbers(){
    for(unsigned int i;i<input.length();i++){
        if(input.at(i) == '0'){
            numbers[i]++;
        }
    }
}

My error:

When I enter my string, the value always returns 0. Any idea why?

Était-ce utile?

La solution

Post your Counter class definition As one of the comments correctly stated, I can see no way counter sees the same input var.

Edit: then based on your code the fix should be replace in main

getline(cin, input);

with

getline(cin, test.input);

and remove

string input;

Autres conseils

Here is my solution.

int main()
{
    string input;
    cout << "Enter a string\n";
    getline(cin, input);

    Counter test(input);  // highlight
    test.countcharacters();
    test.countnumbers();
}

You need to call the constructor of class Counter and transfer 'input' to Counter::input (of course, you need to add a constructor with a string as the parameter). Or you can write a function as below:

void Counter::setInput(string _input)
{
    this.input = _input;
}

and call this function before you start counting.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top