#include <cctype>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void main() {
string input;
vector<string> words;
int i,p;
while (getline(cin,input))
{
i=p=0;
if (input=="exit") break;
while (i<=input.length())
{
if (isspace(input[i]) || i==input.length())
{
words.push_back(input.substr(p, i-p));
p=i+1;
}
i++;
}
cout << input << endl;
for(i=0; i<=(words.size()-1); i++) cout<<words[i] << endl;
words.erase(words.begin(), words.end());
}
}
string parser comments
kay this is my first attempt at making a string parser. it seems to work fine but i''m unsure if it is conventional or not.
any comments?
Have a look at stream iterators. I can't remember exactly, but I think this is how you would make something nice and generic. Oh, and I'd put your parsing into a separate function.
Sorry, but I don't have a compiler on this machine, so I haven't tested this. I might have made a few silly mistakes, but just play around with it.
Edit: Yes, silly mistake. :]
[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]
[edited by - Lektrix on September 21, 2003 4:40:38 PM]
#include <iostream>#include <vector>#include <string>#include <sstream>#include <iterator>#include <algorithm>// think that's all you need... :] template <class Container, typename CharT, typename Traits>void parse(Container& c, const std::basic_string<CharT, Traits>& str){ std::basic_istringstream<CharT, Traits> iss(str); std::copy(std::istream_iterator<std::basic_string<CharT, Traits>, CharT, Traits>(iss), std::istream_iterator<std::basic_string<CharT, Traits>, CharT, Traits>(), std::back_inserter(c));} templaete <class Container, typename CharT, typename Traits>void parse(Container& c, const std::basic_istream<CharT, Traits>& is){ std::copy(std::istream_iterator<std::basic_string<CharT, Traits>, CharT, Traits>(is), std::istream_iterator<std::basic_string<CharT, Traits>, CharT, Traits>(), std::back_inserter(c));} int main() { std::vector<std::string> vec; std::string input; while (std::getline(std::cin, input) && input != "exit") parse(vec, input); /* or parse(vec, std::cin); and force EOF*/ std::copy(vec.begin(), vec.end(), std::ostream_iterator<std::string>(std::cout, "\n")); std::cout << "Press any key to exit..."; std::cin.get(); return 0;}
Sorry, but I don't have a compiler on this machine, so I haven't tested this. I might have made a few silly mistakes, but just play around with it.
Edit: Yes, silly mistake. :]
[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]
[edited by - Lektrix on September 21, 2003 4:40:38 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement