不确定我做错了什么,但这是我的代码
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;
}
输出混乱并返回从未在数据文件中开始的东西
答案 0 :(得分: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 :(得分:0)
如果我们将您的代码翻译成英语,我们会得到:
注意一个大问题:我们在实际读取之前检查值是否为-1。我们需要颠倒步骤1和2的顺序,以便得到:
我们可以通过使用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.
}
}
答案 2 :(得分:-1)
注意:优良作法是,如果使用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.
}