user19604272
user19604272

Reputation: 25

C++ Error: error: expected unqualified-id before string constant

What should I do in this line of code (highlighted by comment) ?

# include <iostream>

int main()
{
    int occurrences = 0;
    std::string::size_type start = 0;
    std::string base_string = "Hello World in C++!";
    std::string to_find_occurrences_of = "o","+"; // error

    while ((start = base_string.find(to_find_occurrences_of, start)) != std::string::npos) {
        ++occurrences;
        start += to_find_occurrences_of.length();
}
    std::cout<<occurrences;
    return 0;
}

I want string to_find_occurrences_of = "o","+" to print the two characters in one time (but IDE raises an error) because I do not want to define the string (and the function) over and over again to find the occurrences of the characters in string base_string one by one.

It may sound like a stupid question, but I want to know the solution to this error.

Thank you to anyone who may be reading this question or answering!!!

Upvotes: 0

Views: 1172

Answers (2)

doctorlove
doctorlove

Reputation: 19232

std::string to_find_occurrences_of = "o","+"; won't compile, because you have two strings, rather than one.

You could just have an initialiser list of the things to find:

int main()
{
    int occurrences = 0;
    // std::string::size_type start = 0; // need to reset for each character
    std::string base_string = "Hello World in C++!";
    for (std::string to_find_occurrences_of : { "o", "+" }) // OK
    {
        std::string::size_type start = 0; // start from the beginning for each character
        while ((start = base_string.find(to_find_occurrences_of, start)) != std::string::npos) {
            ++occurrences;
            start += to_find_occurrences_of.length();
        }
    }
    std::cout << occurrences;
}

Upvotes: 2

C&#233;sar Debeunne
C&#233;sar Debeunne

Reputation: 518

You can use a std::vector of string instead:

# include <iostream>
# include <vector>

int main()
{
    int occurrences = 0;
    std::string::size_type start = 0;
    std::string base_string = "Hello World in C++!";
    std::vector<std::string> to_find_occurrences_of;
    to_find_occurrences_of.push_back("o");
    to_find_occurrences_of.push_back("+");
    
    for (size_t i = 0; i < to_find_occurrences_of.size(); i++){
        start = 0;
        while ((start = base_string.find(to_find_occurrences_of.at(i),start)) != std::string::npos) {
        ++occurrences;
        start += to_find_occurrences_of.at(i).length();
    }
}
std::cout<<occurrences;
return 0;

}

Upvotes: 0

Related Questions