Home > Mobile >  C Error: error: expected unqualified-id before string constant
C Error: error: expected unqualified-id before string constant

Time:09-28

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!!!

CodePudding user response:

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;
    std::string base_string = "Hello World in C  !";
    for (std::string to_find_occurrences_of : { "o", " " }) // OK
    {
        while ((start = base_string.find(to_find_occurrences_of, start)) != std::string::npos) {
              occurrences;
            start  = to_find_occurrences_of.length();
        }
    }
    std::cout << occurrences;
}

CodePudding user response:

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;

}

  • Related