Hello Jo1152,
"getline" will read the entire line including the new line character, but discards the new line not storing it in the string.
Searching the string for a new line character will not find one. It will pick up on the "\t", but will work only if the paragraph is indented for the first line.
When you put something in single quotes it can only contain
one character. This,
line_[i] == '\n\n')
, will cause a compile error because it is not a single character.
Your for loop and if statement will not work because there is no new line in the string and should there be a "\t" it does not mean that it is a new paragraph.
If you want to count paragraphs it would work better to count blank lines.
The following code presents several concepts that I will cover after:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
void paragraphcount()
{
const std::string inFileName{ "Textfile.txt" };
int counter{ 1 };
std::string line;
std::ifstream inFile(inFileName);
if (!inFile)
{
std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3)); // <--- Needs header files chrono" and "thread".
/*return 1;*/ exit(1); // If not in "main".
}
while (std::getline(inFile, line))
{
std::cout << line << std::endl;
//line_.length(); // <--- This line does nothing.
//for (size_t i = 0; i < line.length(); ++i)
//{
// if ((line == "") || line[i] == '\t')
// counter++;
//}
if (line == "")
counter++;
}
inFile.close();
std::cout << "\nThere are " << counter << " paragraphs" << '\n';
}
|
Over time I have found the beginning code to be the most useful for opening an input file.
Line 1 creates a variable with the file name.
Line 8 creates a variable (or handle) for a file stream and what is in the () will open the file all at one time.
The if statement on line 10 the condition is the simplest way to check if the file is not open.
Line 13 is optional as is the header files that it needs. I use this with my IDE setup to have time to read the message before the window closes when the program ends.
Line 14 will exit the program because there is no reason to continue until the problem is fixed.
With your method you are missing an else statement to describe the problem.
The comment on line 21 says what is wrong.
Line 29, in place of the for loop, checks for a blank line in order to add one to the "counter". Notice that I also started the "counter" at 1 instead of zero.
All this is based on your test file. I need to set up a better file to check this.
Hope that helps,
Andy