fork(1) download
  1. #include <vector>
  2. #include <string>
  3. #include <cstring>
  4. #include <iostream>
  5.  
  6. #define MAX_A 40
  7. #define MAX_B 3
  8. #define MAX_C 40
  9. #define MAX_D 4
  10.  
  11. struct Foo {
  12. char a[ MAX_A ];
  13. char b[ MAX_B ];
  14. char c[ MAX_C ];
  15. char d[ MAX_D ];
  16. };
  17.  
  18. template <std::ptrdiff_t N>
  19. const char* extractToken(const char* inIt, char (&buf)[N])
  20. {
  21. if (!inIt || !*inIt)
  22. return NULL;
  23.  
  24. const char* end = strchr(inIt, '@');
  25. if (end)
  26. {
  27. strncpy(buf, inIt, std::min(N, end-inIt));
  28. return end + 1;
  29. }
  30. strncpy(buf, inIt, N);
  31. return NULL;
  32. }
  33.  
  34. template <std::ptrdiff_t N>
  35. std::string display(const char (&buf)[N])
  36. {
  37. std::string result;
  38. for(size_t i=0; i<N && buf[i]; ++i)
  39. result += buf[i];
  40. return result;
  41. }
  42.  
  43. int main(int argc, const char *argv[])
  44. {
  45. std::string input = "abcd@efgh@ijkl@mnop";
  46.  
  47. Foo foo = { 0 };
  48.  
  49. const char* cursor = input.c_str();
  50. cursor = extractToken(cursor, foo.a);
  51. cursor = extractToken(cursor, foo.b);
  52. cursor = extractToken(cursor, foo.c);
  53. cursor = extractToken(cursor, foo.d);
  54.  
  55. std::cout << "foo.a: '" << display(foo.a) << "'\n";
  56. std::cout << "foo.b: '" << display(foo.b) << "'\n";
  57. std::cout << "foo.c: '" << display(foo.c) << "'\n";
  58. std::cout << "foo.d: '" << display(foo.d) << "'\n";
  59. }
  60.  
Success #stdin #stdout 0.01s 2860KB
stdin
Standard input is empty
stdout
foo.a: 'abcd'
foo.b: 'efg'
foo.c: 'ijkl'
foo.d: 'mnop'