IoIiderp

Comma seperated string list to std::list<int>

Sep 20th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <list>
  5.  
  6. bool isSeperator(char c);
  7. bool isNumber(char c);
  8.  
  9. int main()
  10. {
  11.     std::string input; // Input that gets used in each part of the main function.
  12.     std::string buffer; // A buffer meant to help process the input.
  13.  
  14.     std::cout << "Please enter a bunch of numbers seperated with commas." << std::endl;
  15.     std::getline(std::cin, input);
  16.  
  17.     // Remove non seperators or numbers
  18.     buffer = input;
  19.     input = "";
  20.     for( char c : buffer )
  21.     {
  22.         if( isNumber(c) or isSeperator(c) )
  23.         {
  24.             input.push_back(c);
  25.         }
  26.     }
  27.  
  28.     // Create list with numbers in string format.
  29.     std::list<std::string> str_numbers;
  30.     buffer = "";
  31.     for( char c : input )
  32.     {
  33.         if( isNumber(c) )
  34.             buffer.push_back(c);
  35.  
  36.         if( isSeperator(c) )
  37.         {
  38.             if(buffer.size() > 0)
  39.             {
  40.                 str_numbers.push_back(buffer);
  41.                 buffer = "";
  42.             }
  43.         }
  44.     }
  45.  
  46.     // Convert string numbers into int numbers.
  47.     std::list<int> int_numbers;
  48.     for( std::string str : str_numbers )
  49.     {
  50.         int num;
  51.         std::istringstream ss(str);
  52.         ss >> num;
  53.         int_numbers.push_back(num);
  54.     }
  55.  
  56.     // Print the numbers
  57.     for( int num : int_numbers )
  58.         std::cout << num << std::endl;
  59. }
  60.  
  61.  
  62. bool isSeperator(char c)
  63. {
  64.     if(c == ',')
  65.         return true;
  66.  
  67.     if(c == ';')
  68.         return true;
  69.  
  70.     if(c == '&')
  71.         return true;
  72.  
  73.     return false;
  74. }
  75.  
  76. bool isNumber(char c)
  77. {
  78.     return (c>='0' && c<='9');
  79. }
Advertisement
Add Comment
Please, Sign In to add comment