问题
This program should read a paragraph from a text file provided by the user and then store each line in a ragged char array and count the total number of words and lines of the paragraph then display the result.
I can't figure out why does the number of lines keep giving me the result of 3 and why the number of words is always missing 2 words.
please help and keep in mind that I'm no professional just started learning c++ recently.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
ifstream infile;//declarations
char filename[45];
char **data = 0;
char **temp = 0;
char *str = 0;
char buffer[500], c;
int numoflines = 0, numofwords = 0;
cout << "Please enter filename: ";//prompt user to enter filename
cin >> filename;
infile.open(filename);//open file
if (!infile)//check if file was successfully opened
{
cout << "File was not successfully opened" << endl << endl;//display error message
return 0;
} //end of if
data = new char*[numoflines];
while (!infile.eof())
{
temp = new char*[numoflines + 1];
for (int i = 0; i < numoflines; i++)
{
infile.getline(buffer, 500);//read line
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
str = new char[strlen(buffer) + 1];//allocate a dynamic array
strcpy(str, buffer);
data[i] = str;
temp[i] = data[i];
}//end of for
infile.getline(buffer, 500);
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
temp[numoflines] = new char[strlen(buffer) + 1];
strcpy(temp[numoflines], buffer);
delete[] data;
data = temp;
numoflines++;
}
cout << "Number of words: " << numofwords << endl;
cout << "Number of lines: " << numoflines << endl;
return 0;
}
回答1:
The concept of number of lines is a viewing concept only. It's not encoded into the file. The following single paragraph can be displayed on one line or 16 lines depending upon the size of the editor window:
If you wanted to specify a char width of the window, lines could be calculated from that, but as is, paragraphs and wordcount are as good as you will do. And given a successfully opened ifstream infile
that is fairly simple to obtain:
auto numoflines = 0;
auto numofwords = 0;
string paragraph;
while(getline(infile, paragraph)) {
numofwords += distance(istream_iterator<string>(istringstream(paragraph)), istream_iterator<string>());
++numoflines;
}
cout << "Number of words: " << numofwords << "\nNumber of lines: " << numoflines << endl;
NOTE:
Visual Studio supports inline construction of an istringstream
so if you're not using that you'll need to construct on a separate line.
来源:https://stackoverflow.com/questions/40547206/how-do-i-count-words-and-lines-that-were-input-as-a-cstring-array