Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

my do-while loop doesn't end

Tags:

c++

do-while

i'm new to c++ so sorry if this question is really simple.i'm writing a program in c++ that rolls a dice and shows it's number until the user types the word cancel but my loop doesn't end even though i type cancel.here is my code(i use dev c++):

#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int dice (int);
int main()
{
    char k[7];
    int x;
    do
    {
          cout<<"your dice number is: "<<dice(x)<<endl;
          cout<<"do you want to cancel or continue?";
          cin>>k;
     }while(k!="cancel");
          cout<<"END";
          getch();
}
int dice (int a)
{   
    srand(time(NULL));
    for(int i=1;i<100;i++)
        {
            a=(rand()% 6)+1;
        }
            return a;        
}
like image 204
user2589043 Avatar asked Dec 16 '22 08:12

user2589043


1 Answers

It will never be true because you are comparing pointers not the actual string content. Yet another reason you should use std::string (the comparison operator for this will compare the string itself).

The C way of doing this comparison is to use strcmp, the C++ way is to use std::string and rely on it's comparison operators (namely operator==). But since this is tagged C++ I strongly suggest you use std::string.

You can find the documentation for strcmp here and the one for std::string here.

like image 83
Borgleader Avatar answered Dec 31 '22 16:12

Borgleader