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

string and char variable was not declared in this scope C++

本文关键字:字符串 char 变量 未声明 范围      更新时间:2023-10-16

我想创建一个能够计算字符的程序。

这是我的代码:

#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 was not declared.原因是什么原因?

您应该阅读有关范围的信息。C 中的变量在范围中具有可见性和寿命,在该范围中被声明。例如,输入字是可见的,并且仅在第一个do-while循环中存在。将其声明移到循环上方。您的代码有许多这样的错误。此外,我看不到,在哪里宣布对方,应适当初始化。

您将许多变量名称和使用的变量混合在其范围之外。这是您的代码的工作版本,并进行了一些调试:

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

您将inputWord声明为字符串,请检查您的编译器是否适用于此,因为某些编译器不使用指定器"字符串"。您的程序也缺少searchChcounterword。首先正确声明这些变量。

您应该在开始循环之前定义" inputword",例如:

string inputWord = "";

做 {

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

因为" inputword"在循环内部,

相关文章: