-1

I have an array of strings and I'd like to assort the elements by real datatype ("1" -> int; "abc" -> string; "1a" -> string) :

#include <iostream>
#include<vector>

int main() {
  std::vector<std::string> number;
  std::vector<std::string> str;
  
  std::string arr[5] = {"1","1a","ab","10.1","a2"};
  for(int i = 0;i<5;i++){
    if(arr[i] /* is string */){
      str.push_back(arr[i]);
    }
    else if(arr[i] /* is int */){
      number.push_back(arr[i]);
    }
  }
  
  return 0;
}

What is the simplest way?

Thanks!

gsztesi
  • 9
  • 2
  • 2
    They are all strings. Are you trying to detect if string contains digits only? – Yksisarvinen May 11 '22 at 08:12
  • `"34326742367482423784628394628462394632784"`. According to your goal, is that a string or an int? -- *What is the simplest way?* -- There is no "simplest" way, as "simplest" is a matter of opinion. – PaulMcKenzie May 11 '22 at 08:16
  • Personally I'd try to convert to (1) integral type, (2) decimal type, (3) anything else, and if the attempt passes then it's that type. – Bathsheba May 11 '22 at 08:19
  • Does this answer your question? [How to determine if a string is a number with C++?](https://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c) – Biffen May 11 '22 at 08:24
  • 1
    What is the actual high-level problem you are trying to solve? This is looking like an [XY Problem](https://xyproblem.info/) – PaulMcKenzie May 11 '22 at 08:26

1 Answers1

1

If your goal is to only examine whether a string contains integer/decimal or not, you can try a solution with regexes:

if(std::regex_match(arr[i], std::regex("[-|+]?[0-9]*[.,]?[0-9]+")))
  number.push_back(arr[i]);
else 
  str.push_back(arr[i]);

I'm assuming you're not taking overflow into account because you're only using strings, otherwise if you wanted to convert strings to numbers, you'd have to take that into account and use other solutions.

arorias
  • 318
  • 3
  • 14