Home > Mobile >  My variables are not assigned correctly I think [duplicate]
My variables are not assigned correctly I think [duplicate]

Time:10-08

I'm new to C , trying to make a simple program that runs prime number from 3 to 300 but there seems to be this problem:

main.cpp:23:27: error: no match for ‘operator ’ (operand types are ‘std::string’ {aka ‘std::__cxx11::basic_string’} and ‘int’)

What are the mistakes in my code? I know there's plenty, but I appreciate any support to point them out for me, thanks.

int main() {
    int i = 0;
    int num = 0;
    string prime = "";
    
    for (i = 3; i <= 300; i  ) {
        int counter = 0;
        for (num = i; num >= 1; num--) {
            if (i % num == 0) {
                counter = counter   1;
            }
        }
        if (counter == 2) {
            prime = prime   i   " ";
        }
    }
    cout << "Prime numbers: ";
    cout << prime;
}

CodePudding user response:

Look at the error message carefully. It says that on line 23 you are trying to do an addition operation ( ) where the left side is a string and the right side is an int. You did not post your full code, so I am not sure exactly where line 23 is, but I suspect it is this line:

prime = prime   i   " ";

Instead of trying to add an integer to a string, you should convert the integer to a string first. Try something like this:

prime = prime   std::to_string(i)   " ";

CodePudding user response:

you can replace line prime = prime i " "; with prime = prime to_string(i) " ";

This problem is occurring since you're trying to add a string to an integer, String should be added to other strings/characters only.

CodePudding user response:

You should convert the int variable i to a string before concatenating it to prime:

prime = prime   to_string(i)   " ";

CodePudding user response:

Other answers show how to use std::to_string() to solve the problem.

Another solution is to use std::ostringstream instead of std::string, let operator<< format the int to text for you, eg:

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    ostringstream prime;

    for (int i = 3; i <= 300; i  ) {
        int counter = 0;
        for (int num = i; num >= 1; num--) {
            if (i % num == 0) {
                  counter;
            }
        }
        if (counter == 2) {
            prime << i << " ";
        }
    }
    cout << "Prime numbers: ";
    cout << prime.str();
}
  •  Tags:  
  • c
  • Related