【问题标题】:identifier "numIDs" is undefined while inside of scope标识符“numIDs”在范围内未定义
【发布时间】:2021-10-04 23:40:47
【问题描述】:

我正在编写一个小应用程序,它应该从文本文件中获取一串数字,然后将它们保存到数组中,最后通过迭代打印数组,文件应该是这种格式:

10 0 1 2 3 4 5 6 7 8 9

第一个数字是应该在数组中的数字或“ID”的数量,其余的是 this 的元素。

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

int main() {
    ifstream test;
    test.open("test.txt");
    string s;
    getline(test, s);
    int numtest = s[0];
    for (int  i = 0; i < numtest; i++) {
        string currLine;
        getline(test, currLine);
        int numIDs = currLine[0];
        int arrayIDs[numIDs];
        for (int j = 2, k = 0; j < numIDs; j += 2, k++) {
            arrayIDs[k] = currLine[j];
        }
    }
    test.close();
    for (int i = 0; i <= numIDs; i++) {
        cout << arrayIDs[i];
    }
}

但是,我得到了错误

identifier "numIDs" is undefined

identifier "arrayIDs" is undefined

分别在第 22 行和第 23 行,虽然我不知道为什么,但据我了解,因为这两个是变量,所以 #include 不应该有任何问题,并且都在 main() 函数内,所以我不明白为什么它们将是未定义的。

【问题讨论】:

  • 这些项目仅在您的第一个 for 循环的生命周期内存在。您的第二个循环引用了它看不到的名称。
  • numIDsfor 循环的范围内定义。它不存在于它之外。如果要在循环结束后使用它,则需要将其移出循环。 i &lt;= numIDs 将索引数组超出范围,arrayIDs[k] = currLine[j]; 将为您提供数字的 ascii 值,而不是数字本身。 currLine[j] - '0' 可以工作,但您的解决方案很脆弱。只需使用&gt;&gt; 将数字直接读入数组即可。 stringstream 可以提供帮助。
  • 您也可以考虑使用std::vector 而不是int arrayIDs[numIDs];。可变长度数组不是标准的 C++ 并且不适用于所有编译器。
  • 顺便说一句,numIDs = curLine[1] 行不会从您的示例数据行中产生值10。这只会得到第一个字符,即'1'。由于是字符类型,numIDs 将具有字符表示的值,在 ASCII 中为 49。

标签: c++ arrays undefined


【解决方案1】:

放置在循环内的变量在循环外将不可见。因此,要解决您的问题,请在循环之外而不是在循环中声明 numIDs。此外,从外观上看,您可能希望将第二个循环放在第一个循环中。 原文:

int numtest = s[0];
for (int  i = 0; i < numtest; i++) {
    string currLine;
    getline(test, currLine);
    int numIDs = currLine[0];
    int arrayIDs[numIDs];
    for (int j = 2, k = 0; j < numIDs; j += 2, k++) {
        arrayIDs[k] = currLine[j];
    }
}

修订:

int numtest = s[0];
int numIDs = 0;
for (int  i = 0; i < numtest; i++) {
    string currLine;
    getline(test, currLine);
    numIDs = currLine[0];
    int arrayIDs[numIDs];
    for (int j = 2, k = 0; j < numIDs; j += 2, k++) {
        arrayIDs[k] = currLine[j];
    }
    for (int i = 0; i <= numIDs; i++) {
        cout << arrayIDs[i] << ' ';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多