将数字从文本文件读取到数组中
Reading numbers from textfile into array
我一直在玩这个,但我一无所获。 我正在尝试将整数列表从 txt 文件读取到数组 (1,2,3,...)。 我知道将读取的整数数量为 100,但我似乎无法填充数组。 每次我运行代码本身时,它只为所有 100 个整数存储值 0。 有什么想法吗?
//Reads the data from the text file
void readData(){
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile){
//error handling
cout << "File can't be read!";
}
else{
int a;
while (inputFile >> a){
int numbers;
//Should loop through entire file, adding the index to the array
for(int i=0; i<numbers; i++){
DataFromFile [i] = {numbers};
}
}
}
}
要从 istream 中读取单个整数,您可以这样做
int a;
inputFile >> a;
这就是您在 while 循环中所做的。while 很好,因为对于流(在文件)中的每个整数,您将执行 will 的块
这inputFile >> a
一次读取一个整数。 如果放入测试中(如果/同时),真值将回答"是否已读取该值?
我不明白你试图对你做什么number
变量。由于没有由您初始化,它就像它的值0
一样,最终使 foor 循环无法运行
如果你想准确地读取100
整数,你可以这样做
int *array = new int[100];
for (int i=0; i<100; ++i)
inputFile >> array[i];
否则你可以保留一个计数器
int value;
int counter = 0;
while(inputFile >> value && checksanity(counter))
{
array[counter++] = value;
}
你没有读a
到你的numbers
中,把你的代码改成这样:
if (!inputFile){
//error handling
cout << "File can't be read!";
}
else{
int a;
while (inputFile >> a){
//Should loop through entire file, adding the index to the array
for(int i=0; i<a; i++){
DataFromFile [i] = a; // fill array
}
}
}
如果您正在循环访问文件,则每次都会用新数字覆盖数组。这可能不是您打算做的。您可能想用 100 个不同的号码填写 100 个位置?在这种情况下,请使用以下代码:
if (!inputFile){
//error handling
cout << "File can't be read!";
}
else{
int i = 0;
while (inputFile >> a){ // Whilst an integer is available to read
DataFile[i] = a; // Fill a location with it.
i++; // increment index pointer
}
}
相关文章:
- 从锯齿状数组读取
- 是否很好地定义了强制转换为仅由 char[] 组成的结构并从该数组读取?
- 如何按字符从文件到2D数组读取字符
- 双维数组读取错误
- 动态分配的数组C 读取句子并打印单词
- ESP8266异常在尝试从字节数组读取float时
- C++无法从 2D 字符串数组读取
- Win32 C/C++从字节数组读取BMP宽度和高度
- 在执行期间将大型多维数组读取和写入二进制文件并返回数组
- 从 BYTE 数组读取 32 位整数.VC++
- 从十六进制数组读取 Int
- 从十六进制数组读取双精度到向量
- 通过数组C++读取学生的成绩
- 使用迭代器数组读取稀疏信息
- 从文件到字符串再到数组读取数字
- 直接从数组读取时超出了绑定地址
- 转换为空指针后从char数组读取int值
- 动态数组读取
- 从字节数组读取类型的模板方法的问题
- 从文件中以单独的数组读取整数,每次一个数字,在c++中