简体   繁体   中英

File isn't being read? (C++)

I am attempting to read numbers from a text file into a program, but for some reason, the program isn't reading the file. Here is my code:

#include <iostream>
#include <stream>
using namespace std; 

int main()
{

ifstream infile; 

infile.open ("adventDay1.txt"); 

if (!infile) { //Check if file is opening 

    cerr << "Error!"<< endl;

    return 0; 
}

int dataSize = 0;
infile >> dataSize; 
int* arr; 
arr = new int[dataSize]; //dynamically allocated array

int measureCount = 0; //Keep track of input from file 


for (int i = 0; i < dataSize; i++) {

   // infile >> dataSize; 

    arr[i] = dataSize;

    measureCount += 1; 
}

 cout << measureCount << endl; 

delete[] arr; //Delete dynamically allocated memory 
return 0; 
}

Each time I run it, it just displays the "Error." message I added, There are 2,000 numbers in the text file. so that should be the expected output based on what I have here. I can't pinpoint the mistake.

Include fstream and ensure that you are opening the file in read mode. Perhaps also define it as ifstream infile("adventDay1.txt")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM