Reputation: 1
a bit new here, been back and forth trying to solve the issue of getline. Which I found the source of the error was due to intext[18]. Once I remove the array all errors go away. Problem is the document I have has 19 lines of data I need to retrieve so rather than typing out each string I decided to attempt to put it all in array. I am very new to c++ and this is the only time so far that I have hit a wall. I do apologize in advance if this has been solved. Ive been searching all day without resolve.
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <array>
using namespace std;
int main()
{
ifstream inFile;
string intext[18];
inFile.open("HW3_Data_W.txt");
while (inFile.is_open()) {
getline(inFile, intext);
cout << "Data from the file:" << endl;
cout << "Item 1: " << intext << endl;
break;
inFile.close();
}
}
Upvotes: 0
Views: 81
Reputation: 11
You're trying to assign string value to string array variable, you should
getline(inFile, intext[i]);
where i
is the number of line.
Also your array can only contain 18 lines of text, because you declared it this way. If you want to read files that have exactly 19 lines you should declare it this way:
string intext[19];
If you want your program to read any number of lines you should use std::vector.
Besides that, your while loop will only repeat once. because you break it unconditionally. I guess what you wanted to do is something like that:
inFile.open("HW3_Data_W.txt");
int i = 1;
while (inFile.is_open()) {
getline(inFile, intext[i]);
i = i + 1;
cout << "Data from the file:" << endl;
cout << "Item 1: " << intext << endl;
if(inFile.eof) continue;
inFile.close();
}
This code should work but is unnecessarily complicated. Your while condition checks if your file is open, but it will be open until you close it and you want to close it when you reach the end of the file. So your while condition look like that: while (getline(inFile, intext[i])) getline will return value that is convertible to false if it reaches last line of your file so your while will go until you read while file. And you have to check if file is open before your while, then you should close file after while. So something like that:
inFile.open("HW3_Data_W.txt");
int i = 0;
if(!inFile.is_open())
return EXIT_FAILURE;
while(getline(inFile, intext[i])) {
cout << "Item "<<i<<": " << intext[i] << endl;
}
inFile.close()
Upvotes: 1
Reputation: 26800
Some issues here:
If you have 19 lines to read, then the size of the string array should be at least 19.
Check if the file is opened successfully only once. No need to check in the while
condition.
Read into consecutive elements of intext
array within while
using a counter which is initialized to 0 before the while loop. Increment this counter within the while
loop.
Remove break
from while
as you want to read the whole file.
Do not close ifstream
inside the while. Do it after the while
loop.
Upvotes: 0