尝试读取数据文件,存储在数组中并打印所有元素,但它不起作用
trying to read data file, store in array and print all the elements but it isnt working
不确定我做错了什么,但这是我的代码
int main (){
int marks [100];
int i=0;
ifstream inputfile;
ofstream outputfile;
inputfile.open("data.txt");
if(!inputfile.is_open())
{
cout<< "File did not open"<< endl;
return 0;
}
cout<<"Marks in File:"<<endl;
while (marks [i] != -1)
{
inputfile>>marks[i];
cout << marks[i] <<endl;
i++;
}
return 0;
}
输出被搞砸了,并返回了数据文件中从未出现过的内容
下面是从文件中读取数据并将其写入控制台的最小代码。说明添加为注释
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream configrecord("D:\Temp\temp.txt"); // opening the file named temp for reading.
if(configrecord.good()) // check whether the file is opened properly.
{
string line;
while (getline(configrecord, line)) // reading a line from file to std::string
{
cout << line; // printing the line, if you want it to store in an array, you can use the std::string::data() api to get the character pointer.
}
configrecord.close(); // closing the file after reading completed
}
}
如果我们将您的代码翻译成英语,我们会得到:
- 检查当前数组元素是否为 -1,如果是,则中断循环。
- 将值读入当前数组元素。
- 输出值。
- 移动到下一个数组元素并重复。
注意一个大问题:我们在实际读取之前检查值是否为 -1。我们需要颠倒步骤 1 和 2 的顺序,以便我们得到:
- 将值读入当前数组元素。
- 检查当前数组元素是否为 -1,如果是,则中断循环。
- 输出值。
- 移动到下一个数组元素并重复。
我们可以通过使用 true
作为循环条件,然后使用 if 语句在循环的后面检查输入的值是否为 -1,如果是,则使用 break
来中断循环。
#include <fstream>
#include <iostream>
//using namespace std; is considered bad practice
int main()
{
std::ifstream inFile("input.txt");
int marks[100];
//check if file is open stuff...
for(int i = 0; true; i++)
{
inFile >> marks[i];
if(marks[i] == -1) break;
std::cout << marks[i] << 'n'; //endl flushes the buffer, unnecessary here.
}
}
注意:如果使用 if 语句,则还包括 else 语句是一种很好的做法。此外,您的 while 循环令人困惑,因为如果遇到负数,它会停止,所以我假设你知道整数 -1 不在文件中。
int n = -1;
if(!inputfile.is_open())
{
cout<< "File did not open"<< endl;
}
else
{
cout<<"Marks in File:"<< endl;
while(!inputfile.eof()){ // .eof is bad practice, but for this instance it works.
File >> marks[n];
n++; // Essentially the size of the array (Number of values), keeping track of how many values there are will assist you in the output process.
}
}
读取完文件后,应将其关闭,然后使用数组中的数据。
inputfile.close();
最后,为了输出数据数组,您必须使用 for 循环或某种类型的迭代器来访问存储在数组中的值。
for(int i=0; i < n ; i++) // Output array. Where array size is less than n.
{
cout << marks[i] << " "; // " " inputs a space in between each word.
}
相关文章:
- 从控制台中删除最后打印的元素
- 数组元素打印的递归方法
- 打印所有链表的元素 (C++)
- 更新的矢量元素不打印
- 打印矢量数组中的所有元素
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 如何在c ++中打印给定桶号的所有元素unordered_set?
- 为什么平均打印数组元素比打印单个对象慢C++?
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- C++ Expat 仅打印元素的第一个字母和标签中的数据
- 如何在 2D 字符数组中打印 [x][y] 元素的地址?(C++)
- C 打印元素总和
- C 打印元素,带有来自对象数组的数据
- 将数组传递到空隙函数,然后递归打印元素
- 使用std :: lower_bound()打印元素范围以下某些值以下
- 3D 指针数组的打印元素
- 如何打印元素的地图内部的矢量
- 中缀,前缀或后缀顺序通过BST得到降序打印元素
- 从列表中打印元素
- 如何在矢量 c++ 中打印元素