0

I dont know why this wont work;


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>

using namespace std;

int main() {
    string guess;
    bool gameStarted = false;
    int number;

    srand(time(NULL));
    number = rand() % 10 + 1;

    system("pause");
    gameStarted = true;
    while(gameStarted) {
        cout << "Guess: ";
        getline(cin, guess);

        int guessI = atoi(guess);

        if(guessI == number) {
            cout << "True guess";
            system("pause");
            return 0;
        }

        if(guessI != number) {
            cout << "False guess";
            continue;
        }
    }

}

I am making an number guessing game but when I use atoi() to convert a string to an int it will give an error. Why is that? Im pretty new to C++ but i have knowledge of Python and stuff. I have been trying to fix this for so long. Am I missing an library or something? The error;

C:\Users\arenc\Documents\Number guessing game\c++\main.cpp|24|error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'|

1 Answers1

1

You're trying to convert string to an int without using .c_str() and hence, conversion fails.

You should use: int guessI = std::atoi(guess.c_str()); instead. Hope it helps.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34