字符串和char变量未在此范围C ++中声明

时间:2018-02-15 07:35:42

标签: c++

我是编程的新手,我想问一个错误 我想创建一个能够计算单词中字符的程序

这是我的代码

/*
write a program that will ask the user to input a word that is at least 5 characters in length
once a valid word has been inputed, ask the user to input a character. the program will then
calculate the number of times this inputed character appears in the word and output the result
*/

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

int main()
{
// ask the user to input the word, at least contain 5 characters
    do
    {
    string inputWord = "";
    cout << "please enter your word to be counted = \n";
    cin >> inputWord;
    }while(inputWord.size() < 5);

// ask the user to input a character
    do
    {
        char searchCh = '0';
        cout << "please enter a character from \n" << inputWord;
        cin >> searchCh;
    }while(searchCh.size()<1 && searchCH.size()>1);

// iterate over the word
    for(int i=0;i < (int) inputWord.size(); i++)
    {

    // get the character
        char ch = word.at(i);
    // if the character matches the character we're looking for
        if(searcCh==ch)
        // increment counter
        {
            counter++; // counter = counter + 1
        }
    }

// output the number of times character appears
    cout << "the word " << word << " contain character " << searchCh << "is" << counter;

    return 0;
}

我总是得到错误inputWord没有声明,你能帮我解决这个错误???

4 个答案:

答案 0 :(得分:0)

您应该阅读有关范围的内容。 c ++中的变量在范围内具有可见性和生命周期,其中声明了变量。例如,inputWord是可见的,仅存在于第一个do-while循环中。将其声明移到循环上方。您的代码有很多这样的错误。而且,我没有看到,计数器声明在哪里,应该正确初始化。

答案 1 :(得分:0)

你将输入字声明为字符串,请检查你的编译器是否适用于此。因为某些编译器不采用说明符&#34;字符串&#34;。另外&#34; searchch&#34;,&#34 ;计数器&#34;和&#34;字&#34;你的程序也缺少。首先要正确地声明这些变量。

答案 2 :(得分:0)

你混淆了很多变量名,并在其范围之外使用了变量。 以下是代码的工作版本,其中包含一些调试:

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

int main()
{
// ask the user to input the word, at least contain 5 characters
string inputWord = "";
char searchCh = '0';
char ch;
int counter=0;
    do
    {

    cout << "please enter your word to be counted = \n";
    cin >> inputWord;
    }while(inputWord.size() < 5);

// ask the user to input a character

        cout << "please enter a character from \n" << inputWord;
        cin >> searchCh;

// iterate over the word
    for(int i=0;i < (int) inputWord.size(); i++)
    {

    // get the character
         ch = inputWord[i];
    // if the character matches the character we're looking for
        if(searchCh==ch)
        // increment counter
            counter++; // counter = counter + 1
    }

// output the number of times character appears
    cout << "the word " << inputWord << " contain character  " << searchCh << " is " << counter;

    return 0;
}

答案 3 :(得分:0)

您应该在启动while循环之前定义“ inputWord”,如下所示:

string inputWord = "";

做 {

cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);

因为“ inputWord”位于循环内,