尝试读取数据文件,存储在数组中并打印所有元素,但它不起作用

trying to read data file, store in array and print all the elements but it isnt working

本文关键字:打印 元素 不起作用 数组 数据 读取 文件 存储      更新时间:2023-10-16

不确定我做错了什么,但这是我的代码

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,如果是,则中断循环。
  2. 将值读入当前数组元素。
  3. 输出值。
  4. 移动到下一个数组元素并重复。

注意一个大问题:我们在实际读取之前检查值是否为 -1。我们需要颠倒步骤 1 和 2 的顺序,以便我们得到:

  1. 将值读入当前数组元素。
  2. 检查当前数组元素是否为 -1,如果是,则中断循环。
  3. 输出值。
  4. 移动到下一个数组元素并重复。

我们可以通过使用 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.
}