没有在此作用域c++中声明变量

A variable was not declared in this scope c++

本文关键字:声明 变量 c++ 作用域      更新时间:2023-10-16

我必须为Uni做这个程序,并且我一直收到这个"变量未在此范围内声明"错误。这是任务:

编写一个函数,该函数以字符串和整数数组为参数,并返回一个字符串,其中字符串参数中的每个字符根据整数数组中的相应值相乘。您可以假设(除了字符串的终止字符null/0之外)两个数组都有相同数量的元素。此外,函数应该在引用参数中返回结果中的额外字符数。示例参数1"abcd"{1,2,3,4}结果:"abbccdddd"6

这是我迄今为止成功编写的代码:

#include <iostream>
#include <string>
using namespace std;
string Function (string c, int numbers[n])
{
string result;
for ( int i=0; i< n;i++)
{
int index= numbers[i];
for (int j=0; j< index;j++)
{
result.append(c.at(i));
}
}
return result;
}
int main ()
{
int n;
string r;
cout << "Nr in array";
cin >> n;
int numbers [n];
for ( int i=0; i<n;i++)
{
cout << "Nr";
cin >> numbers[i];
}
string c;
cout << " Write some letters";
cin >> c;
r=Function(c,numbers[n]);
cout << r;
return 0;   
}

这些是当我试图编译代码时弹出的错误:

4:40: error: 'n' was not declared in this scope
In function 'std::string Function(...)':
7:20: error: 'n' was not declared in this scope
9:14: error: 'numbers' was not declared in this scope
12:18: error: 'c' was not declared in this scope
In function 'int main()':
33:25: error: cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string<char>}' through '...'

我知道这可能是一个微不足道的解决方案,在发布这篇文章之前,我已经在stackoverflow上搜索过类似的问题,但我认为没有什么能真正解决我的问题。我的意思是,我不会在主函数之后定义函数,也不会在循环中定义变量,然后在循环之外调用它们。提前感谢!:)

用于传递数组的语法无效。您应该将指针(数组实际上就是指针)及其长度作为一个单独的参数进行传递。

此外,当以这种方式分配数组时,您需要提前了解数组的大小,因为您无法在运行时决定这一点。这就是new的动态内存分配的用途,如下所示。请记住始终释放已分配的内存,以确保没有内存泄漏。

#include <iostream>
#include <string>
using namespace std;
// numbers is a pointer and n is the length of it
string Function (string c, int* numbers, int n)
{
string result;
for ( int i=0; i< n;i++)
{
int index= numbers[i];
for (int j=0; j< index;j++)
{
result += c.at(i);
}
}
return result;
}
int main ()
{
int n;
string r;
cout << "Nr in array";
cin >> n;
// allocate dynamic memory in desired size
int* numbers = new int[n];
for ( int i=0; i<n;i++)
{
cout << "Nr";
cin >> numbers[i];
}
string c;
cout << " Write some letters";
cin >> c;
r=Function(c,numbers, n);
cout << r;
// free previously allocated memory
delete[] numbers;
return 0;
}

您不需要将数组长度传递给函数,因为您知道字符串和数组的长度相同。另外,在C++中不能这样做:cin >> n; int numbers [n];,因为n不是常量表达式。您可以改用int *numbers=new int[n];

#include <iostream>
#include <string>
using namespace std;
string Function (const string &c, int* numbers)
{
string result;
for (size_t i=0; i<c.size(); i++)
result.append(numbers[i],c.at(i));
return result;
}
int main ()
{
int n;
cout << "Nr in array: ";
cin >> n;
int *numbers=new int[n];
for (int i=0; i<n; i++)
{
cout << "Nr: ";
cin >> numbers[i];
}
string c;
cout << "Write some letters: ";
cin >> c;
cout << Function(c,numbers) << endl;
delete[] numbers;
return 0;
}