Mar 10, 2011 at 6:46am UTC
When I try to run the program, it comes up with this error window:
http://i.imgur.com/M1ClO.jpg
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <iostream>
#include <string>
#include <sstream>
#include<fstream>
using namespace std;
string BlankSpace(const string & a);
string NumWords(string user_input);
int main()
{
char UserInput[256];
fstream Lines;
Lines.open( "lines.txt" );
cout << "Enter your string " << endl;
while ( Lines.getline(UserInput, 256) )
cout << BlankSpace(UserInput) << endl;
string userinput= BlankSpace(UserInput);
string numwords= NumWords(userinput);
cout << "There are " << numwords << "words in your string." << endl;
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;
}
string NumWords(string user_input)
{
int numspaces;
char nextChar;
string NumSpaces;
numspaces= 0;
for (int i=0; i< int (user_input.length()); i++)
{
nextChar = user_input.at(i);
if (isspace(user_input[i]))
numspaces++;
}
NumSpaces= numspaces;
return NumSpaces;
}
Last edited on Mar 10, 2011 at 6:59am UTC
Mar 10, 2011 at 10:29am UTC
Your code throws an exception of type length_error;
http://www.cplusplus.com/reference/std/stdexcept/length_error/
Have a look at this line;
result.erase(result.end()-1);
If it looks fine to you, no worries; stick some debugging code just ahead of it so you can get some information on every result you pass into it. Take a look at the usual sorts of things; what characters are actually in the string, how big the string is, that sort of thing.
Last edited on Mar 10, 2011 at 10:36am UTC