主要由成员函数访问的用户输入

时间:2013-07-17 03:51:41

标签: c++ input return-value counter member-functions

我有这段代码:

#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]++;
        }
    }
}

我的错误:

当我输入我的字符串时,该值总是返回0.知道为什么吗?

2 个答案:

答案 0 :(得分:1)

发布您的Counter类定义 正如其中一条评论正确陈述的那样,我看不出计数器看不到相同的输入var。

编辑:然后根据您的代码修复应该是 在主

中替换
getline(cin, input);

getline(cin, test.input);

并删除

string input;

答案 1 :(得分:0)

这是我的解决方案。

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

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

您需要调用类Counter的构造函数并将'input'传递给Counter::input(当然,您需要添加一个带有字符串作为参数的构造函数)。或者您可以编写如下函数:

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

并在开始计数之前调用此函数。

相关问题