gpt4 book ai didi

c++ - 稍后在程序中使用在 if else 构造内声明的变量会导致未声明的标识符错误

转载 作者:行者123 更新时间:2023-11-28 03:02:05 25 4
gpt4 key购买 nike

这个程序是不言自明的,所以我不会真正深入了解它的目的。

我现在的主要问题是在第 82、89、95 和 101 行,我在编译时遇到了“arr”和“input”的“Undeclared Identifier”错误。

这是因为我在 if else if 构造中声明了它们吗?如果是这样,有什么办法可以解决这个问题。提前感谢您的帮助!!!!

这是代码

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

template<class T> void selectionSort(T arr[], T num)
{
int pos_min;
T temp;

for (int i = 0; i < num - 1; i++)
{
pos_min = i;

for (int j = i + 1; j < num; j++)
{
for (arr[j] < arr[pos_min])
{
pos_min = j;
}
}


if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}

int main()
{

char check = 'C';

while (toupper(check) != 'Q')
{
char dataType;
int num = 0;

cout << "What kind of data do you want to sort?" << endl;
cout << " For integer enter i, for string enter s, for character enter c. ";
cin >> dataType;

//User input dataType
if (toupper(dataType) == 'I')
{
int arr[100];
int input;
cout << " You've chosen Integer dataType" << endl;
}
else if (toupper(dataType) == 'S')
{
string arr[100];
string input;
cout << " You've chosen String dataType" << endl;
}
else if(toupper(dataType) == 'C')
{
char arr[100];
char input;
cout << " You've chosen Character dataType" << endl;
}
else
{
cout << "Not a recognizable dataType. Shuting down..." << endl;
return -1;
}

//User input # of num
cout << "How many num will be sorted? ";
cin >> num;

for (int i = 0; i < num; i++)
{
cout << "Enter an input of the dataType you selected: ";
cin >> input;
arr[i] = input;
}

//Display user input
cout << "The data as you entered it: ";
for (int i = 0; i < num; i++)
{
cout << arr[i];
cout << " ";
}
cout << endl;

//Sort user input by calling template functon selectionSort
selectionSort(arr, num);

//Display sorted user input
cout << "After sorting your data by calling selectionSort: ";
for (int i = 0; i < num; i++)
{
cout << arr[i];
cout << " ";
}

cout << endl;
//Query user to quit or continue
cout << " Would you like to continue? Enter 'Q'. Enter anything else to continue.";
cin >> check;

}



return 0;
}

最佳答案

这是因为您在 if/else block 中声明了它们。一旦 block 完成,这些变量就会离开scope。并且不再可访问。
解决此问题的一种方法是始终将输入作为字符数据读入,然后在事后将其转换为指定的类型。参见 atoi了解如何将 char 转换为 int。

关于c++ - 稍后在程序中使用在 if else 构造内声明的变量会导致未声明的标识符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com