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