Reputation: 43
I'm trying to read a file line by line and insert the lines into an array, but it won't compile. I'm using VS code and it highlights arr[line] and when I hover over it is says "no operator "[]" matches these operands". Can someone tell me what I'm doing wrong?
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
char arr[4];
string line;
ifstream file;
file.open("input.txt");
if(file.is_open()) {
while (getline(file, line))
{
file >> arr[line]; // the problem is with this line
}
file.close();
}
return 0;
}
Upvotes: 0
Views: 378
Reputation: 91
There is some scope of improvement in your code. When you are reading from file you don't know how many lines it contains. so to store those lines instead of using fixed size containers like array try to use dynamic size containers like vector.
here is example:
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> mylines;
string line;
ifstream file;
file.open("input.txt");
if(file.is_open()) {
while (getline(file, line))
{
mylines.push_back(line);
}
file.close();
}
for(int i=0;i<mylines.size();i++)
cout<<mylines[i]<<endl;
return 0;
}
Upvotes: 2
Reputation: 483
You're trying to access an array, using a string as an index, which is invalid in C++.
In plain English, this means you are telling the compiler to "Store the data from array with index called line into the file".
Then the compiler doesn't know what you want to do, because strings are not a supported type for array indexing.
I recommend reading more about indexing arrays here: https://www.cpp.edu/~elab/ECE114/Array.html
And you can try using the code located here: How to read lines of text from file and put them into an array
Upvotes: 3