My program immediately exits after it asks for a character [duplicate] - c

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 1 year ago.
I hope you are doing well everyone. I was given this homework by my teacher.
Which is the problem below:
Write a program that will ask for n positive whole numbers. Your program will only stop asking for a number if the input number is 0 or < 0. From these inputs, determine all the prime numbers. After determining the prime numbers, write a menu option shown below:
[A] Display One’s
[B] Display Ten’s
[C] Display Hundred’s
[D] Display Thousand’s
If the user presses on of these options, then it will display what is being asked. To further understand and shorten the instructions, an illustration is provided below.
Input numbers: 123, 112, 1377, 2, 13, 0
Prime numbers: 123 1377 2 13
If the user presses ‘A’, then the output is
123 = 3
1377 = 7
2 = 2
13 = 3
If the user presses ‘B’, then the output is
123 = 23
1377 = 77
2 = 0
13 = 13
If the user presses ‘C’, then the output is
123 = 123
1377 = 377
2 = 0
13 = 0
If the user presses ‘D’, then the output is
123 = 0
1377 = 1377
2 = 0
13 = 0
I've written a program that I thought would solve the problem, but somehow after I input a character (A,B,C,D) the program immediately terminates?
If someone could point any other mistakes or have any suggestions in mind. I'll be open to them and I'll be grateful. Thanks so much in advance. :))
#include<stdio.h>
int isPrime(int num);
void Sort(char sort, int psize, int* prime);
int main ()
{
int psize=0;
int i, num=1;
int arr[1000], prime[1000];
char sort;
do
{
printf("Enter array element:");
scanf("%d", &num);
if(num<=0) break;
if(isPrime(num))
{
prime[psize]= num; //assign to prime array if it is a prime
psize++;
}
} while(num>0);
printf("\nEnter [A] to Display One's\nEnter[B] Display Ten's\nEnter[C]Display Hundred's\nEnter[D]Display Thousand's");
scanf("%c", &sort);
Sort(sort, psize, prime);
}
int isPrime (int num)
{
int i, flag=1;
for(i=2;i<num;i++)
{
if(num%i==0)
{
flag=0;
break;
}
}
return flag;
}
void Sort(char sort, int psize, int* prime)
{
int i, ans;
if(sort == 'A'){
printf("Ones\n");
for(i=0;i<psize;i++)
{
ans = prime[i] % 10;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'B'){
printf("Tens\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 10)
ans = prime[i] % 100;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'C'){
printf("Hundreds\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 100)
ans = prime[i] % 1000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'D'){
printf("Thousands\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 1000)
ans = prime[i] % 10000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
}

I think that will help you out.
put a fflush() after your scanf function like:
scanf("%d", &num);
fflush(stdin);
Or you use a easier way
int getNumber()
{
char userinput = '1';
int number = 0;
/*
Ascii-table
0 = 48
1 = 49
...
9 = 57
*/
while(1)
{
userinput = getchar();
if (userinput == '\n') break;
if (userinput >= 48 && userinput <= 57)
number = (number * 10) + (userinput - 48);
}
return number;
}
Replace your scanf("%d", &num); with num = getNumber(); - that works!
So, here another code with A-D letters
I hope this will be enough now - And all useres forgive me for my uncomplete code review ^^" :
int getNumber( int opt )
{
char userinput = '1';
int number = 0;
/*
Ascii-table
0 = 48
1 = 49
...
9 = 57
*/
while(1)
{
userinput = getchar();
if (userinput == '\n') break;
/*
opt (Options)
1: Numbers
2: Letters A-D
Other numbers undefined!
*/
switch(opt)
{
case 1:
/* Only 0-9 allowed */
if (userinput >= 48 && userinput <= 57)
number = (number * 10) + (userinput - 48);
break;
case 2:
/* Only A-D allowed */
if (userinput >= 'A' && userinput <= 'D')
number = userinput;
break;
default:
/* Nothing to do - wrong input */
number = 0;
break;
}
}
return number;
}
Replace your scanf("%d", &num); with num = getNumber(1);
Replace your scanf("%d", &sort); with sort = getNumber(2);

Related

Counting the number of zero in an integer

The program would ask the user an integer input.
and it counts how many zero the int has.
constraints: use while loop
ex:
input: 2400
count: 2
now I have no problem in that part, only when the user would input a zero.
supposed it counts 1.
ex:
input 0
count: 1
but then the program returns count 0.
here's the code:
int main(){
int n, counter = 0;
printf("Enter the number: ");
scanf("%d", &n);
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
printf("%d", counter);
return 0;
}
Use functions.
int countZeroes(int x)
{
int result = !x; // if x == 0 then result = 1
while(x)
{
result += !(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
printf("%d\n", countZeroes(0));
printf("%d\n", countZeroes(1000));
printf("%d\n", countZeroes(-202020));
}
https://godbolt.org/z/91hKr46eo
You have while(n != 0) this does so when you enter just 0 it doesn't run. So the counter that you have set to 0 at the beginning is still 0
Here is what I would have done :
int main()
{
int num, count = 0;
scanf("%d",&num);
if (num == 0) {
printf("1");
return 0;
}
while(num != 0) //do till num greater than 0
{
int mod = num % 10; //split last digit from number
num = num / 10; //divide num by 10. num /= 10 also a valid one
if(mod == 0) count ++;
}
printf("%d\n",count);
return 0;
}
Just don't forget to consider everything that can happen with a condition that you set
**Fixed it
A different version that prints the integer as a string, and looks for '0' characters in it. Tested.
#include <stdio.h>
#include <string.h>
int main(void)
{
int input = 0;
int zeroes = 0;
char *foundpos, teststring[100];
scanf("%d", &input);
sprintf(teststring, "%d", input);
foundpos = strchr(teststring, '0');
while (foundpos != NULL) {
++zeroes;
foundpos = strchr(foundpos + 1, '0');
}
printf("%d contains %d zeroes", input, zeroes);
}
Just count the zero digits you get between \n chars.
#include <stdio.h>
int main()
{
int ndigs = 0, c;
while ((c = getchar()) != EOF) {
switch (c) {
case '0': ndigs++;
break;
case '\n': printf(" => %d zero digs", ndigs);
ndigs = 0;
break;
}
putchar(c);
}
}
sample output:
$ ./a.out
123001202010
123001202010 => 5 zero digs
^D
$ _
No need to convert digits to a number, to convert it back to decimal digits. You can improve the program counting digits until a nondigit is detected, then output. But there's no need to convert a decimal representation of a number (in base 10) to internal representation to then get the digits you have destroyed (in the conversion) back again to count them.
As earlier mentioned, the problem is with the loop:
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
It doesnt do anything in case n == 0. But replacing it with n > 0 is not a good solution because ints can be negative too.
You should use do{}while() construction instead, it will always do one iteration of loop no matter what condition you put there. Notice that no matter what you get as a number, it is still a number so you can do one iteration of loop either way.
Just do as follows:
do{
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
} while( n != 0 );
This should work(if i didnt mess up the braces/semicolumns).

How can check if the digits of a number are prime and if so multiply them in C

The problem says that the user will input numbers till he inserts 0 (exit) then if there are any prime digits in that given number, the program shall multiply them.
For example:
input : 4657
output : 35 ( 5 * 7 )
Here is what I have tried so far but I cannot pull it off with the multiplication... my code might look a little bit clumsy, I am a beginner :)
int main() {
int number;
int digit, prime;
int i, aux;
int multiplier;
input:
printf("Give Number :");
scanf("%d", &number);
do {
multiplier = 1;
digit = number % 10;
number = number / 10;
printf("%d \n", digit);
prime = 1;
for (i = 2; i <= sqrt(digit); i++) {
if (digit % 1 == 0) {
prime = 0;
}
}
if (prime != 0) {
multiplier = multiplier * digit;
}
} while (number != 0);
printf("The result : %d\n", multiplier);
goto input;
return 0;
}
There are multiple problems in your code:
missing #include <stdio.h>
use of label and goto statement to be avoided at this stage.
testing for prime digits can be done explicitly instead of a broken loop.
digit % 1 == 0 is always true, you should write digit % i == 0 (maybe a typo from copying someone else's code?
i <= sqrt(digit) will not work unless you include <math.h> and still a bad idea. Use i * i < 10 instead.
0 and 1 should not be considered primes.
it is unclear what the output should be if none of the digits are prime, let's assume 1 is OK.
Here is a modified version:
#include <stdio.h>
int main() {
for (;;) {
int number, multiplier;
printf("Give Number :");
if (scanf("%d", &number) != 1 || number <= 0)
break;
multiplier = 1;
while (number != 0) {
int digit = number % 10;
number = number / 10;
if (digit == 2 || digit == 3 || digit == 5 || digit == 7)
multiplier *= digit;
}
printf("The result: %d\n", multiplier);
}
return 0;
}

How to split an arbitrary long input integer into pair of digits?

Expected Input:
123456
Expected output:
12
34
56
I have tried in this way
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, count = 0;
int value = 10000;
/*This for input validation. User can give exactly 6 digit as an input If
user breaks this condition then It
will redirect back to take input again */
while (1)
{
int countUpdate = 0;
int quotientUpdate = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
while (quotientUpdate != 0)
{
quotientUpdate = numberUpdate / 10;
numberUpdate = quotientUpdate;
countUpdate++;
}
if (countUpdate > 6 || countUpdate < 6)
{
printf("It allows exactly 6 digits\n");
}
else
{
break;
}
}
//This for finding the pair of two consecutive digits.
while (quotient != 0)
{
count++;
if (count == 4)
{
break;
}
quotient = number / value;
remainder = number % value;
if (count != 2)
printf("%d\n", quotient);
if (count == 1)
{
number = remainder;
}
else
{
number = quotient;
}
if (count == 1)
{
value = value / 1000;
}
if (count == 3)
{
remainder = remainder * 10 + 6;
printf("%d\n", remainder);
}
}
return 0;
}
My problem is: I have made this for the exact input 6 digits. From my code, I did not get the expected output. Output comes from my code like:
If a user gives an input 987654
Output shows:
98
76
56
But my expectation is:
98
76
54
Here is another problem: this code does not work for less than 6 or greater than 6 digits. But I want to solve this problem for any number of digit.
Can you help me identifying and solving my problem?
Your solution is a bit overcomplicated.
If you want to use integers, you could do it like this (untested).
Depending on range for your number, you might change to long long.
#include <stdio.h>
int main(void)
{
int number;
int digits = 1;
while (digits & 1)
{ // loop until we get an even number
printf("Enter a number: ");
int ret = scanf("%d", &number);
if (ret != 1)
continue;
// count number of digits
digits = 0;
while (number != 0)
{
number /= 10;
digits++;
}
if (digits & 1)
printf("Please enter even number of digits.\n");
}
// If we are here, we have 2, 4, 6, ... digits
// Calculate divider to chop first 2 digits
int divider = 1;
while (digits > 2)
{
divider *= 100;
digits -= 2;
}
// chop remaining digits and print 2 of them
while (divider)
{
pair = (number / divider) % 100;
printf("%d\n", pair);
divider /= 100;
}
return 0;
}
Another option would be to use strings instead of numbers and then simply print 2 characters per line.
I've updated your code a bit, it should be working and handle the "0" digit within the code. For the "0" digit at the beginning of the code, you should input a string and not a number.
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, count = 0;
int countUpdate = 0;
int value = 10000;
/*This for input validation. User can give exactly 6 digit as an input If
user breaks this condition then It
will redirect back to take input again */
while (1)
{
int quotientUpdate = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
while (quotientUpdate != 0)
{
quotientUpdate = numberUpdate / 10;
numberUpdate = quotientUpdate;
countUpdate++;
}
if (countUpdate < 2 || countUpdate % 2 != 0)
{
printf("Even number of digits only\n");
}
else
{
break;
}
}
count = countUpdate / 2;
numberUpdate = number;
int d[count];
for (int i = 0; i < count; i++)
{
d[i] = numberUpdate % 100;
numberUpdate /= 100;
}
for (int i = count - 1; i >= 0; i--)
{
if (d[i] < 10) printf("0");
printf("%d\n", d[i]);
}
return 0;
}
Before proposing my solution, I'll try to explain what's wrong in your code.
Analysis of the original code
First of all, since you have currently the fixed length limitation, your loop that checks if the number has exactly 6 digits can be omitted; the same check can be performed just checking the range:
if (number < 1000000 || number > 999999)
{
printf("It allows exactly 6 digits\n");
}
else
{
break;
}
The core of your logic is in the loop while (quotient != 0). It contains a lot of strange attempts you perform in order to compensate the previous mistake. It leads to the final reminder with a single digit instead of two, so you try to compensate it with this line
remainder = remainder * 10 + 6;
this obviously works only if the last digit is 6.
The root of the problem is in this row:
if (count == 1)
{
value = value / 1000;
}
But why 1000? value represents the divider in the next loop, so you want it to obtain a reminder with two digit less (instead of 3), so the correct division is value = value / 100;.
All the subsequent correction come after this one. The other answers widely cover the correct solution storing the input within an integer.
A solution involving strings
Since you need a solution with any number of digits, you must be aware that using an int you'll be able to manage at most 10 digits (because the maximum value of an integer is INT_MAX (2147483647).
Using an integer you'll only be limited by the size of the string buffer you choose.
That's the code. Our only limitation is forcing the user to insert only an even number of digits:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
// Put variables for further proceed
char number[101] = { 0 };
int isValid = 0, count = 0;
/*Input validation */
while(!isValid)
{
count = 0;
isValid = 1;
char *p = number;
printf("Enter a number: ");
scanf("%100s", number);
/* Check the validity of the string */
while(*p != '\0')
{
count++;
if(!isdigit(*p))
{
isValid = 0;
break;
}
p++;
}
if( !(isValid = isValid && ( count % 2 == 0 ) ) )
printf("Please insert an even number of digits (numbers only)\n");
}
/* Print the digits*/
for(int i=0; i<count; i+=2)
printf("%c%c\n", number[i], number[i+1] );
return 0;
}
I defined an array of 101 characters (100 + one for the string terminator) and I say scanf to store up to 100 characters (%100s)
I complicated a bit the input validator just to avoid to loop twice through the string (the first using strlen(), needed to check the even digits requirement,and the second to check the digits-only requirement)
In the end I just print two characters at a time using %c format specifier reading them from the string number
The output:
Enter a number: 1234567 // Test the check on an input with an odd number of digits
Please insert an even number of digits (numbers only)
Enter a number: 1234567A // Test the check on an input containing a non-digit char
Please insert an even number of digits (numbers only)
Enter a number: 1234567890123456 // Well formed input
12
34
56
78
90
12
34
56
Here is my solution to this problem. Hope it satisfy your requirement.
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, temp,count = 0;
int value = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
temp = number;
if(number < 100) {
printf("%d",number);
} else {
while(numberUpdate > 100) {
value = value*100;
numberUpdate = numberUpdate/100;
}
while (temp > 0)
{
temp = number/value;
number = number%value;
value = value/100;
printf("%d\n",temp);
}
}
return 0;
}

while loops , int vs char reading from scanf , true and false

#include <stdio.h>
int main()
{
int number; // We make 1 int named number
scanf("%d",&number); // We give to number some number xd
while (number!=0)// We made a loop while if number isn't 0 do that
{
printf("text");// print text
scanf("%d",&number); // and get again a number.
// So everything works well beside inserting some char instead of int.
// So what is the problem wont scanf return 0 so we exit the program not
// just printing a text all day? That's my first question.
}
return 0;
}
The second problem is how to make a program reading numbers from keyboard till I enter some special sign for ex '.' Yea we do it with loop while right? But how when scanf("%d",&something) it give me back 0 if I enter everything but number?
change it from scanf int to char
Assumption: You are reading a single char at a time
#include <stdio.h>
int main()
{
char c = "0";
int n = 0;
while (n != 46)// we made a loop while if char isn't '.' ASCII - 46 do that
{
scanf(" %c", &c);
n = (int)c;
printf("text %d", n);
//Add if statement to confirm it is a number ASCII 48 - 57 and use it.
}
return 0;
}
EDIT:
Just some more info on how to use numbers:
input number one by one or just a whole number like 123 with some ending special char like ';' or change the line
scanf(" %c", &c);
to:
scanf("%c", &c);
this way it will register '\n' as ASCII 10
use that with atoi to get the actual int value and use it.
EDIT 2:
#World, you cannot expect to read only numbers and '.'
One way to do this with your own code is:
#include <stdio.h>
int main()
{
char c = "0";
int n = 0;
int number = 0;
while (n != 46)// we made a loop while if char isn't '.' ASCII - 46 do that
{
scanf("%c", &c);
n = (int)c;
if (n>=48 && n<=57) {
number *= 10;
number += (n-48);
}
if (n==10) {
printf("text %d\n", number);
//Use number for something over here
number = 0;
}
}
return 0;
}
EDIT 3:
Logic behind this:
Let's say you enter 341 in the console
the line
scanf("%c", &c);
will read this one by one thus reading '3', '4', '1' and '\n' respectively
the while loop
while (n != 46)
will thus run 4 times where:
1st time
c = '3';
n = 51;
if (n>=48 && n<=57) is true;
number = 0 * 10;
number = number + n - 48 = 0 + 51 - 48 = 3
2nd time
c = '4';
n = 52;
if (n>=48 && n<=57) is true;
number = 3 * 10 = 30;
number = number + n - 48 = 30 + 52 - 48 = 34
3rd time
c = '1';
n = 49;
if (n>=48 && n<=57) is true;
number = 34 * 10 = 340;
number = number + n - 48 = 340 + 49 - 48 = 341
4th time
c = '\n';
n = 10;
if (n>=48 && n<=57) is false;
if (n==10) is true;
it prints "text 341" and sets number to 0
while loop exits when c = '.' and n = 46
how to make a program reading numbers from keyboard till I enter some special sign for ex '.'
When scanf("%d",&number) returns 0, there is some non-numeric input. Read that non-numeric input with alternate code.
#include <stdio.h>
int main() {
while (1) {
int number;
int scan_count = scanf("%d", &number);
if (scan_count == EOF) break; // End-of-file or rare input error.
if (scan_count != 1) {
int ch = fgetc(stdin);
if (ch == '.') break; // Expected non-numeric input to break the loop.
printf("Unexpected input character '%c'\n", ch);
} else {
printf("Expected numeric input: %d\n", ch);
}
} // endwhile
printf("Done\n");
}
A better approach is to ditch scanf() and use fgets()` to read user input. Then process the inputted string.

C | Comparison between two groups of arrays

I'm pretty fresh in the computers world and started to work on c.
now i'm building a little project about generating code (shown below):
My main:
#include <stdio.h>
#include "connect.h"
#define EASY 20
#define NORMAL 15
#define HARD 10
#define CRAZY 30
int main ()
{
int choice = 1;
char enter, returnV;
system("cls");
printf("Welcome to ""THE MAGSHIMIM CODE BREAKER""!!!\n");
printf("\n");
printf("A secret password was chosen to protect the credit card of Pancratius,\nthe descendant of Antiochus\n");
printf("Your mission is to stop Pancratius by revealing his secret password.\n");
printf("the rules are the follows:\n");
printf("\n");
printf("1. In each round you try to guess the secret password (4 distinct digits)\n");
printf("2. After every guess you'll receive two hints about the password");
printf("\nHITS the number of digits in your guess witch were exactly right.\n");
printf("MISSES the number of digits in your guess witch belong to the password but weremiss-placed\n");
printf("3 - if you'll fail to guess the password after a certain number of rounds \tPancratius will buy all the gift to Hanukkah!!!\n");
printf("\n");
printf("Press Enter to continue...\n");
enter = getch();
if (enter = '\n'){
do{
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
if (choice == 1 || choice == 2 || choice == 3 || choice == 4 ){
switch(choice){
case (1):
system("cls");
returnV = levels(EASY);
break;
case (2):
system("cls");
returnV = levels(NORMAL);
break;
case (3):
system("cls");
returnV = levels(HARD);
break;
case (4):
system("cls");
returnV = levels(CRAZY);
break;
switch(returnV){
case('y'):
break;
case('n'):
return 0;
break;
}
}
}
else if (choice != 1 || choice != 2 || choice != 3 || choice != 4 ){
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
}
} while (returnV != 'n');
}
system("PAUSE");
}
header file to connect:
char levels (int level);
"levels" function:
#include <stdio.h>
#include "connect.h"
#include <time.h>
#include <stdlib.h>
char cases (int myCase, char crazyl);
char levels (int level) {
char crazyl = 'n',playerChoice;
switch (level){
case (20):
playerChoice = cases (level,crazyl);
printf ("\n%c\n",playerChoice);
return playerChoice;
break;
case (15):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (10):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (30):
crazyl = 'x';
level = rand() % (25 - 5 + 1);
playerChoice = cases (level,crazyl);
return playerChoice;
}
}
int ranGen (int code1,int code2, int code3, int code4);
char cases (int level,char crazyl)
{
unsigned int check;
char choise = 't',code1,code2,code3,code4;
if(level > 0){
while (level > 0){
if(crazyl == 'n'){
printf("Write your guess (only 1-6, no ENTER is needed) [%d guess left]\n",level);
}
else if (crazyl == 'x'){
printf("Write your guess (only 1-6, no ENTER is needed) [xxx guess left]\n");
}
code1 = getch();
printf("%c",code1);
code2 = getch();
printf("\t%c",code2);
code3 = getch();
printf("\t%c\t",code3);
code4 = getch();
printf("%c\n",code4);
if(code1 > '0' && code1 < '7' && code2 > '0' && code2 < '7' && code3 > '0' && code3 < '7' && code4 > '0' && code4 < '7'){
check = ranGen(code1,code2,code3,code4);
level--;
} else {
printf("\nnot a good number only numbers between 1-6\n");
level--;
}
if (level == 0) {
printf("FOR GOD SAKE WE LOST!!!\n");
printf("The secret password was:\n");
while (choise != 'y' || choise != 'n') {
if (choise != 'y' || choise != 'n') {
printf("keep playing? (y/n):");
_flushall();
scanf("%1c",&choise);
if (choise == 'y' || choise == 'n' ) {
return choise;
} else {
continue;
}
}
}
}
}
}
}
int ranGen(int code1,int code2, int code3, int code4) {
unsigned int ranCode[3],check,code[3];
code[0] = (int) code1 - 48;
code[1] = (int) code2 - 48;
code[2] = (int) code3 - 48;
code[3] = (int) code4 - 48;
do {
ranCode[0] = rand() % (6 - 1 + 1);
ranCode[1] = rand() % (6 - 1 + 1);
ranCode[2] = rand() % (6 - 1 + 1);
ranCode[3] = rand() % (6 - 1 + 1);
} while (code[0] != ranCode[0] || code[1] != ranCode[1] || code[2] != ranCode[2] || code[3] != ranCode[3]);
}
Now my problem is in ranGen function at "levels" paste.
I need to Generate 4 random numbers between 1-6 that different from each other
(1234 is ok, 1878 not ok, 2234 not ok either) and that the user will guess the digits while if he made a correct digits lets say:
generated code = 2345
guess = 1364
The user will get: 1 HIT and 1 MISS while if user will input 2222 he will get 1 HIT and 3 MISSES.
Now im pretty lost here and any help will be great.
I see the problems in your ranGen() function...
you have...
unsigned int ranCode[3],check,code[3];
ranCode[3] gives you 3 elements in that array. Array elements start counting at zero, so that would give you ranCode[0], ranCode[1] and ranCode[2]. If you want ranCode[3] and code[3], than you need to change the above line to...
unsigned int ranCode[4],check,code[4];
That gives you 4 elements, numbered from 0 to 3 (0, 1, 2 & 3 equals 4 numbers).
I'm also not certain what you are trying to do with...
ranCode[0] = rand() % (6 - 1 + 1);
...in your program, it will evaluate what is inside the brackets first, so 6 - 1 = 5, + 1 = 6. So in essence, that line will also look like ranCode[0] = rand() % 6; to the compiler and will give a number from 0 to 5. If you wish to add one to the result, you can use: ranCode[0] = (rand() % 6) + 1;, that would do the random number first, then add one to it for 1 to 6 (which is what I assume you wanted for a dice roll?).
Anyhow, you're passing code4 to a nonexistent element, out of range and probably corrupting memory somewhere, which would have undefined behaviour, possibly crash the system, or effect another variable's memory etc.

Resources