late to soft 132

Chapter ten number 2
Campus safety in asg
Out of pizza

solutions for ch10 number 4 from
http://www.linuxquestions.org/questions/programming-9/c-counting-words-in-a-string-173787/

word counter with iterators
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>

using namespace std;

int main()
{
string msg;

cout << "Type in a string\n";
getline(cin, msg);

istringstream ostr(msg);
istream_iterator<string> it(ostr);
istream_iterator<string> end;

size_t words = 0;
while (it++ != end) words++;

cout << "\nThere are " << words << " words in this string." << endl;

return 0;
}

word counter with for loop
#include <iostream>
#include <string>
using namespace std;

int main()
{
int i, numspaces;
char nextChar;
string msg;

numspaces=1;

cout << "Type in a string\n";
getline(cin, msg);

// checks each character in the string
for (i=0; i<int(msg.length()); i++)
{
nextChar = msg.at(i); // gets a character
if (isspace(msg[i]))
numspaces++;
}
cout << "\nThere are " << numspaces << " words in this string.";
cin.ignore();
return 0;
}

Popular posts from this blog

ch11 review silberschatz operating systems concepts essentials 2nd ed