I submitted this code for eliminating unneeded whitespace from a string and I was told that I need to remove the processing from the main to a function. I've been trying to do this but nothing I have tried works.
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
string BlankSpace(const string & a);
int main()
{
int i;
int NumSpaces;
char NextWord;
string UserInput;
NumSpaces= 0;
cout << "Enter your string " << endl;
getline(cin,UserInput);
cout << endl;
cout << BlankSpace(UserInput) << endl;
cout << endl;
for(i=0; i<int(BlankSpace(UserInput).length()); i++)
{
NextWord= BlankSpace(UserInput).at(i);
if (isspace(BlankSpace(UserInput)[i]))
NumSpaces++;
}
cout << "There are " << NumSpaces + 1 << " words in your string.";
cout << endl;
cin.get();
return 0;
}
string BlankSpace(const string & a)
{
istringstream iss(a);
string result;
string input;
while (iss>>input)
{
result+=input;
result+=' ';
}
result.erase(result.end()-1);
return result;
}
It seems I would have to move where the program counts the amount of whitespace to the BlankSpace function. No idea how to do this, though.
I was also told that my program, though it compiles, it only outputs one line of input. A text document was tested on it and apparently it didn't work. I don't know how to test it with a text document so if anyone could tell me how to do that, I'd greatly appreciate it.
Calculate the number of spaces in a separate function and return that as a value.
As for a text document, your instructor probably just redirected standard input into the file they were testing, which basically means the input from the user became the contents of the text file.
The reason you are only getting one line of input is because you only call getline() once, getting one line of input, perform your processing, then exit without looping.