'How to read paragraphs from a file while avoiding the blank space between them into an array? [closed]
I have been trying to figure this out. I'm very new to C++. I have tried using this: (what modifications would be needed?)
while(!openFile.fail())
{
getline(openFile,myArray[size])
}
My array size is the same as the number of paragraphs. However, I can't figure out how to consider the paragraphs as one element of the array.
Edit [How I did it]:
while(!openFile.fail()) // while no errors keep going.
{
// then i needed a for loop to iterate [size of array] times.
for ( int i = 0; i < sizzArr; i++)
{
getline(tempFile, copyDataF); // this getline gets my first line from the date file into our copyDataF.
while (copyDataF.length() != 0) // when what we copied is not empty
{
arr[i] = arr[i] + copyDataF + "\n";
getline(tempFile, copyDataF); /* assuming next line is blank, our while loop will stop,
the iteration will repeat till end of file (+ depends on the for loop). */
}
}
[ thank you everyone who tried to help as i admit my question wasn't clear enough ]
Solution 1:[1]
I'm not entirely sure what step you're having trouble with, but if I understand correctly. You have a file of some kind that you want to read from and a std::string array initialized to have size equaling the number of lines in the file. You can easily open a file with <ifstream> using open() and then read the file line by line with std::getline(), adding each line to the resultant array.
If you want to perform any further logic (searching for spaces in a line, whatever else) this should be enough to get you headed in the right direction. For context, the ./foo.txt file contains 3 newline separated strings of text.
#include <iostream>
#include <ifstream>
using namespace std;
int main() {
ifstream file;
string line;
file.open("./foo.txt", std::ios_base::in);
string lines[3];
int i = 0;
if (file.is_open()) {
// begin reading the file line by line
while (std::getline(file, line)) {
cout << "line: " << line << endl;
lines[i] = line;
i++;
}
} else {
cout << "error opening file" << endl;
}
cout << "printing array" << endl;
for (int j = 0; j < 3; j++) {
cout << lines[j] << endl;
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
