#include <iostream>
#include <string.h>
usingnamespace std;
//prototype
int processline(char*);
int GetString();
int main()
{
GetString();
}
int GetString()
{
char buffer [300];
while (cin.getline (buffer, 300))
{
int wordCount = 0;
wordCount += processline (buffer);
cout << endl << "There were " << wordCount << " words." <<endl;
}
return 0;
}
int processline (char* buffer)
{
int i, count = 0, beg = 0, out =0;
int length = strlen(buffer);
buffer[length] = ' ';
buffer[length + 1] = '\0';
length += 2;
char output [300];
char space = ' ';
for (i=0; i < length; i++)
{
if (isspace(buffer[i])!= 0)
{
if(i != beg)
{
strncpy((output+out), (buffer+beg), (i-beg));
out += i-beg;
//strcat(output+out, space);
output[out] = space;
out++;
count++;
}
beg = i+1;
}
}
output[out] = '\0';
cout << output << endl;
return count;
}
Originally the problem was that I could not have any input or output in main so I moved that. Now however as a result the txt file i am trying to put in gets reduced line by line instead of staying as a whole paragraph.
Whay is this?
Here is the text(there are supposed to be massive spaces in the text but this website removed them which is the intention of this program.):
Some time ago, a professor of mine was trying to
create a program using a particular toolset. This toolset
had a publicly-declared programming interface, but no means of
restricting access. Unfortunately none of the
documented public interface would let the professor make the program
work as desired. Being clever and resourceful,
the professor figured out how to change some data the
toolset used that was not accessible through the
publicly-declared interface. To the professor's surprise however,
the program still did not work as hoped, changing
the data "behind the scenes" had unintended, collateral
consequences that made the program crash and burn.
Just so the record is clear, let me state
emphatically that my professor was justified in violating
the so-called encapsulation presented by the toolset.
It is not the programmer's job to give up easily
and tell the user, "Sorry, but the toolset doesn't
do what you want". The programmer's job is to
be clever and resourceful and find a way to implement the design
if at all practicable. If the toolset frustrates every devious
attempt to get the program to work as desired,
it is then, of course, the duty of the programmer to publicly
lampoon the toolset's promotional literature and place an
evil curse on the software company that developed it.
The problem is in the way you moved code from main to the new GetString() function. Originally you initialized wordCount before you entered the while loop and printed the results when you finished. Now you re-initialize and print wordCount every time through the loop. Move lines 19 and 23 to before and after the while loop, and your problem will go away.