0

For my code, the user inputs a location's longitude and latitude along with the name of the location. For example, "33.9425/N 118.4081/W Los Angeles International Airport". The program then calculates some information using the longitude and latitude. I'm relatively new to c++, but I thought of using string slicing from python. However, I'm never sure how many digits the coordinates will be, so I can't slice it manually. Is there a way in c++ to only get the digits up to a certain character? For example, only getting 33.9425 and 118.4081?

at26
  • 63
  • 5
  • [`std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline) has an overload that allows you to specify a delimiter other than the usual newline to split on. – user4581301 Apr 16 '19 at 21:55
  • In C++ you can use the `>>` operator to separate words. By default, it will read all characters up to a whitespace from a stream. But there are other ways too. See for example https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string – Valentino Apr 16 '19 at 21:56
  • otherwise good ol `>>` into a `double` will stop as soon as it finds a character that is not a `double`. – user4581301 Apr 16 '19 at 21:56

2 Answers2

0

Yes you can use

string s {"abc"};
s.find("b");

to evaluate the first occurance of a symbol and then use the substr() method to slice the string.

0

This is a classic regex problem. Have a look at std::regex. I might do this myself with std::regex_iterator. This should work:

#include <regex>
#include <iterator>
#include <iostream>
#include <string>

int main()
{
    const std::string s = "33.9425/N 118.4081/W Los Angeles International Airport";

    std::regex words_regex("\\d+\\.\\d+");
    auto words_begin = 
        std::sregex_iterator(s.begin(), s.end(), words_regex);
    auto words_end = std::sregex_iterator();

    std::cout << "Found " 
              << std::distance(words_begin, words_end) 
              << " numbers:\n";

    for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
        std::smatch match = *i;                                                 
        std::string match_str = match.str(); 
        std::cout << match_str << '\n';
    }   
}

Output:

Found 2 numbers:
33.9425
118.4081

Full disclosure: I just pulled the above from cppreference.com's example for std::regex_iterator and changed it, not my own code :)

djhaskin987
  • 9,741
  • 4
  • 50
  • 86