I have this section of code for generating an array of randomly generated and sorted ints, but the nosearch cin quits the program. Calling Cin.ignore() & cin.clear() before and/or after this line does not correct this, no error message is shown, the program just quits as soon as I hit enter on that section. This is the only statement to do this.
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include "search.hpp" //a function called sarch is here, program quits before sarch is called.
using namespace std;
int main () {
srand(time(0));
int tenn;
int minrange;
int maxrange;
cout << "Enter the number of integers: ";
cin >> tenn;
cout << endl << "Enter the lower limit: ";
cin >> minrange;
cout << endl << "Enter the upper limit: ";
cin >> maxrange;
int *arr = new int(tenn*10);
for (int i = 0; i < tenn*10; i++){
*(arr+i) = (rand() % maxrange) + minrange;
}
cout << "list, unsorted: " << endl;
for (int i = 0; i < tenn*10; i++){
cout << *(arr+i) << " ";
}
cout << endl;
for (int i = 0; i < tenn*10; i++){
int low = i;
for (int j = i; j < tenn*10; j++){
if (*(arr+j) < *(arr+low)){
low = j;
}
}
int temp = *(arr+i);
*(arr+i) = *(arr+low);
*(arr+low) = temp;
}
cout << "sorted list: " << endl;
for (int i = 0; i < tenn*10; i++){
cout << *(arr+i) << " ";
}
cout << endl;
int nosearch;
cout << "Enter the number of values you wish to search for: " << endl;
//The next cin will fail
cin >> nosearch;
cout << "v";
//more code here...
I use a makefile to compile the code, and when I run it in terminal, this is what happens:
>./Needle.exe
Enter the number of integers: 2
Enter the lower limit: 0
Enter the upper limit: 10
list, unsorted:
9 4 6 2 4 5 2 9 1 4 7 8 3 4 9 4 6 7 9 9
sorted list:
1 2 2 3 4 4 4 4 4 5 6 6 7 7 8 9 9 9 9 9
Enter the number of values you wish to search for:
3
>
I can only assume something I did above triggered this error, which is why I included so much of the code.
Related
hi guys i recently started learning C++ and today i got a problem with counting divisors in this program
i want my program to count the number of divisors exactly but the output show weird numbers :/
#include <iostream>
using namespace std;
int main(void)
{
int Lowest;
int Highest;
int count = 0;
cout << "Enter The Lowest Number Of Series: ";
cin >> Lowest;
cout << "Enter The Highest Number Of Series: ";
cin >> Highest;
cout << "\n Number -> Divisors ((count)) \n";
for (int i = Lowest; i <= Highest; i++)
{
cout << " " << i << " ->";
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++; // WTF
cout << " " << j;
}
}
cout << " (( count:" << count << " )) " << endl;
}
return 0;
}
for example out put for Lower=1 to Highest=10 is like this:
Enter The Lowest Number Of Series: 1
Enter The Highest Number Of Series: 10
Number -> Divisors ((count))
1 -> 1 (( count:1 ))
2 -> 1 2 (( count:3 ))
3 -> 1 3 (( count:5 ))
4 -> 1 2 4 (( count:8 ))
5 -> 1 5 (( count:10 ))
6 -> 1 2 3 6 (( count:14 ))
7 -> 1 7 (( count:16 ))
8 -> 1 2 4 8 (( count:20 ))
9 -> 1 3 9 (( count:23 ))
10 -> 1 2 5 10 (( count:27 ))
Do you guys have any idea What is Wrong?
As noted by #cigien's comment, your count variable never gets reset to zero so it just keeps counting up. Reset it between each iteration of the outer loop. Better still, move the declaration to the closest place where it's used:
#include <iostream>
using std::cin;
using std::cout; // only using what you need
int main()
{
int Lowest;
int Highest;
cout << "Enter The Lowest Number Of Series: ";
cin >> Lowest;
cout << "Enter The Highest Number Of Series: ";
cin >> Highest;
cout << "\n Number -> Divisors ((count)) \n";
for (int i = Lowest; i <= Highest; i++)
{
int count = 0; // <-- initialize to zero on every pass
cout << " " << i << " ->";
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++;
cout << " " << j;
}
}
cout << " (( count:" << count << " )) \n";
}
return 0;
}
I'm trying to make a Sudoku puzzle generator for a school project, and I have most of the coding and logic worked out for the program, it's just that the random number generator I'm using to assign values to the Sudoku grid are generating numbers far out of the appropriate range, and I can't quite figure out why it's not functioning appropriately.
Here's the code for the number generator:
int Sudoku::RNG(int range, int start){
int randNum;
randNum = (rand()%range+start);
return randNum;
}
I've also seeded with
srand(time(NULL));
at the very start of my main method.
And here's the code for the method which populates the Sudoku grid with numbers from the RNG() function:
void Sudoku::gridPopulate(int grid [9][9]){
Solution s;
int num;
bool safe;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
do{
safe = false;
num= RNG(9,1);
if(s.rowCheck(grid, i, num)&& s.colCheck(grid, j, num) && s.gridCheck(grid, i, j, num)){
grid[i][j] = num;
cout << "Number entered into grid" << endl;
safe = true;
}
}while(safe);
}
}
Main Method:
int main()
{
//Program Start
srand(time(NULL));
int difficulty;
int choice;
int grid[9][9];
cout << "Welcome to my Sudoku puzzle generator! \nTest your mental muscles and see if you can solve the puzzle!" << endl;
//Puzzle Generator
Sudoku game;
game.gridPopulate(grid);
cout << "board populated"<< endl;
cout << "Successful board made" << endl;
game.displayBoard(grid);
}
Example of erroneous Sudoku board below (formatting is off because of the huge numbers, just ignore the dashes and vertical lines):
1 5013192 4981028 9 |20064 8 5 |1 2 3 |
2 8 5 4 |1995768265 0 2114351727 |28 7670880 7670908 |
3 1 7274056 7 |3 0 7670880 |4 6 7670880 |
-----------------4 6 7 2 |4199040 1 8 |7670912 -1196314433 4 |
5 1953657218 1 0 |5 4 32 |7 3 7274140 |
6 5 8 1953722109 |2 9 7670916 |7274116 4199040 4358512 |
-----------------7 0 1953722297 1 |9 1953787893 3 |7274204 4 8 |
8 1953722109 1953722083 8 |4199040 4199040 0 |9 7274160 2 |
9 3 1953746112 1198757840 |6 7274216 4 |4358512 7274368 4358606 |
-----------------
1 2 3 4 5 6 7 8 9
The number's it's giving me are sometimes very large, sometimes not. It's kinda baffling me at the moment, any help or advice would be greatly appreciated!
EDIT/UPDATE #1:
I've revised my gridPopulate code, and I've added in a few cout statements for troubleshooting. The method will now stay on each individual array element until it is populated, the main issue I'm running into now is that the code will get stuck in the do/while statement where the RNG() is occurring. I'm using the counter to track how many RNG iterations it goes through before passing a safe value into the grid. The problem is that the RNG is going through way too many iterations before happening to generate a safe value, sometimes thousands of iterations before moving on. At some point it will just get stuck endlessly generating random numbers without being able to move on.'
void Sudoku::gridPopulate(int grid [9][9]){
Solution s;
int num;
do{
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
int counter = 0;
do{
srand(time(NULL));
num = RNG(9,1);
counter++;
cout << "RNG attempts: " << counter << endl;
}while(!(s.rowCheck(grid, i, num)&& s.colCheck(grid, j, num) && s.gridCheck(grid, i, j, num)));
grid[i][j]=num;
cout << grid[i][j] << endl;
cout << "Row #: " << i << endl;
cout << "Col #: " << j << endl;
}//end j loop
displayBoard(grid);
}//end i loop
displayBoard(grid);
}while(!validityCheck(grid));
Here's my displayBoard method too, though I don't think it is correlated to the problem.
void Sudoku::displayBoard(int grid[9][9]){
/**********************************************************/
cout << " ----------------------" << endl;
for(int i=0; i<9;i++){
if(i==0)
cout << "1 | ";
if(i==1)
cout << "2 | ";
if(i==2)
cout << "3 | ";
if(i==3)
cout << "4 | ";
if(i==4)
cout << "5 | ";
if(i==5)
cout << "6 | ";
if(i==6)
cout << "7 | ";
if(i==7)
cout << "8 | ";
if(i==8)
cout << "9 | ";
for(int j=0;j<9;j++){
cout << grid[i][j] << " ";
if(j==2)
cout << "| ";
if(j==5)
cout << "| ";
if(j==8)
cout << "| ";
}
cout << endl;
if(i==2)
cout << " ------------------------" << endl;
if(i==5)
cout << " ------------------------" << endl;
if(i==8)
cout << " ------------------------" << endl;
}
cout << "\n";
cout << " 1 2 3 4 5 6 7 8 9 " << endl;
/**********************************************************/
}
Nothing wrong with the RNG function, all we need is debugging skills
## Try this to see what is the immediate value of the grid[i][j] ##
`void Sudoku::void gridPopulate(int grid[9][9])
{
Solution s;
int num;
bool safe;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
do {
safe = false;
num = RNG(9, 1);
if (s.rowCheck(grid, i, num) && s.colCheck(grid, j, num) && s.gridCheck(grid, i, j, num)) {
grid[i`enter code here`][j] = num;
//cout << "Number entered into grid" << endl;
safe = true;
}
} while (safe);
cout << grid[i][j] << " ";
}
cout << endl;
}
}`
I'm trying to solve one of the questions on a task sheet I've been received, to help me further in my understanding of C++ code from my class.
The question is (and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen
Creates a second array of size 5 and fills it with zeros
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
The problem is how to go about checking how many times a number was entered. I was thinking of a for loop, but the way I wrote it is fundamentally incorrect, so I find myself struggling to see the mistake I am having. Perhaps I am missing something simple? Any help would be great.
Here is my (terrible) for loop attempt, so you can see my error.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int input[10];
const int MAX_NO = 5;
int COUNT[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
}
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
// show how many times 1 number appears
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
for (int i = 0; i < MAX_NO; i++)
{
cout << i + 1 << " appears " << COUNT[i]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
Put
COUNT[ input[i]-1 ]++;
in your first loop (after validation). Once you do that, you don't need a second loop to tally up the results.
This works from the inside out by first getting what input[i] is, then using it to modify the (input[i]-1)'th location in the COUNT array. If the user enters 4 on the first run of the loop, then i == 0 and input[i] == 4. Since arrays are 0-based, it will increment COUNT[input[i]-1] which in this case is COUNT[4-1] == COUNT[3].
After your initial loop runs the number of 1's will be in COUNT[0], the number of 2's will be in COUNT[1] and so on.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
//declare a constant values
int input[10];
int count = 10; //all constant MUST be in capital letters
//second array filled with zeros
const int MAX_NO = 5;
int COUNT[5] = { 0, 0, 0, 0, 0 };
//ask user for 10 input values
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
//check if input numbers are between 1 and 5 inclusive
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
/* show how many times 1 number appears.
this section should be in the main loop which would enable the program to check how many times a
number is entered so that it is stored in the second array. changed i to secondCount because this is the counting index of the second array not the first which you've called i (one of the reason you'd all zero as output when u ran your code)*/
for (int secondCount = 1; secondCount <= MAX_NO; secondCount++)
{
if (input[i] == secondCount)
{
COUNT[secondCount-1]+= 1; //use minus 1 from i and increment. += 1 is the same as COUNT++
}
}
}
//display number entered in the first array
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
//display how many times a number is entered.
for (int secondCount = 0; secondCount < MAX_NO; secondCount++)
{
cout << secondCount + 1 << " appears " << COUNT[secondCount]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
OUTPUT:
Please enter a number for value 1 = 1
Please enter a number for value 2 = 1
Please enter a number for value 3 = 1
Please enter a number for value 4 = 2
Please enter a number for value 5 = 3
Please enter a number for value 6 = 2
Please enter a number for value 7 = 4
Please enter a number for value 8 = 4
Please enter a number for value 9 = 3
Please enter a number for value 10 = 2
You entered: 1 1 1 2 3 2 4 4 3 2
1 appears 3 times in the input
2 appears 3 times in the input
3 appears 2 times in the input
4 appears 2 times in the input
5 appears 0 times in the input
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
Let's examine what this is doing. It starts by checking input[1]. (This should be input[0] as array indices start at 0). Then it checks if input[1] is equal to 1. If it is, then it increments COUNT[1].
Next, it checks input[2]. Then it checks if input[2] is equal to 2. If it is, it increments COUNT[2]. And so on until it has gone through input[5].
Do you see the problem with this? You're only checking the first 5 inputs and only checking them against a single value.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string.h>
using namespace std;
int main()
{
char pin[6]; //character array to allow for ease of input
int randomNumbers[10]; //holding the randomized numbers that are printed back to the user
int pinStorage[5];
char pinVerify[5];
char pinReenter[6];
int result;
srand(time(0));
cout << "Enter your pin number" << endl;
cin >> pin;
for (int i = 0; i < 5; i++)
{
pinStorage[i] = pin[i] - '0';
}
for (int i = 0; i < 10; i++)
{
randomNumbers[i]= rand() % 3 + 1;
}
cout << "Pin Verify: ";
for (int b = 0; b < 5; b++)
{
for (int d = 0; d <10; d++)
{
if (pinStorage[b]== d)
{
pinVerify[b] = randomNumbers[d];
switch (pinVerify[b])
{
case 1: pinVerify[b] = '1';
break;
case 2: pinVerify[b] = '2';
break;
case 3: pinVerify[b] = '3';
}
cout << pinVerify[b] << " ";
}
}
}
cout << " " << endl;
cout << "Pin : 0 1 2 3 4 5 6 7 8 9" << endl;
cout << "Number: ";
for (int c = 0; c < 10; c++)
{
cout << randomNumbers[c] << " ";
}
cout << " " << endl;
cout << "Renter pin" << endl;
cin >> pinReenter;
for(int h = 0; h < 5; ++h)
{
int digit = pinStorage[h];
pinReenter[h] = randomNumbers[digit] + '0';
}
cout << "PV: " << pinVerify;
cout << "PR: " << pinReenter;
result = (strcmp(pinVerify, pinReenter));
switch(result)
{
case 1: cout << "You did not enter the pin correctly!" << endl;
break;
case 0: cout << "Pin Entered Correctly!" << endl;
break;
case -1: cout << "You did not enter the pin correctly!" << endl;
}
The above is my code. The objective is to be able to enter a normal 5 digit pin such as 12345. The program will then store that pin, and produce a screen like this:
Pin: 0 1 2 3 4 5 6 7 8 9
Num: 3 1 2 3 2 2 3 1 1 3
The program randomized the num part that you see and assigns it to the numbers above. That way the user reenters 12322 and the computer recognizes it as him entering the right code. The next time it where to do it, it would be rerandomized to something else. This whole project is designed to prevent shoulder surfing.
However I seem to be having a problem with my code. Almost everything is working but with the final strcmp function. Even though I have pinVerify set to 5, it still gives me 5 numbers and a ASCII character at the end, something like 21323☻. This makes it impossible to ever have pinVerify and pinReenter as equal, meaning it's impossible for the program to tell you you entered in the challenge correctly, even when you did.
Can anyone help me fix this? I've been looking and tinkering for a while and have been completely unsuccessful.
C-style strings are null-terminated. In your example, it means that, when you want to work with two strings of length 5, you should actually reserve 5+1=6 chars for each of them, and make sure that the 5-th (0-indexed) char contains a character with ASCII code 0. Otherwise, strcmp, and any other C-string function, proceeds past the end of your char[5] array until it finds a byte containing zero.
//Page 215, #2, by Jeremy Mill
//program taken in 7 values, displays them, and then sorts them from highest to lowest, and displays them in order.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Define the variable we will need
const int arraySize = 6;
double dailySales[arraySize];
//Now let's prompt the user for their input
for (int a=0 ; a <= arraySize; a++ )
{
cout << "Please enter sale number " << a+1 << " :";
cin >> dailySales[a];
}
//Now we display the output of the array
cout << "\n\nSale Number" << setw( 13 ) << "Value" << endl;
for ( int i =0; i <= arraySize; i++ )
cout << setw( 5 ) << i << setw( 14 ) << dailySales[ i ] << endl;
//Now we sort using a bubble sort
for(int b = 0; b<=arraySize; b++)
for(int c = arraySize-1; c>=b; c--) {
if(dailySales[c-1] > dailySales[c]) { // if out of order
// exchange elements
int t = 0;
t = dailySales[c-1];
dailySales[c-1] = dailySales[c];
dailySales[c] = t;
cout << "it ran";
}
}
cout << "Now we can display the array again! \n\n\n" << endl << dailySales[6] << endl;
//Now we display the output of the sorted array
cout << "\n\nSale Number" << setw( 13 ) << "Value" << endl;
for ( int d = 0; d <= arraySize; d++ )
cout << setw( 5 ) << d << setw( 14 ) << dailySales[ d ] << endl;
cin.clear(); //clear cin
cin.sync(); //reinitialize it
cout << "\n\nPress Enter to end the program\n\n"; //display this text
cin.get(); //pause and wait for an enter
return 0;
} // end main
Output:
Please enter sale number 1 :1
Please enter sale number 2 :2
Please enter sale number 3 :3
Please enter sale number 4 :4
Please enter sale number 5 :5
Please enter sale number 6 :6
Please enter sale number 7 :7
Sale Number Value
0 1
1 2
2 3
3 4
4 5
5 6
6 7
Now we can display the array again!
7
Sale Number Value
0 1
1 2
2 3
3 4
4 5
5 6
6 2.97079e-313
Press Enter to end the program
Why is it that the last 'value' is not 7, but that number in sci. notation??
Be carreful when looping through your array. The loop has to start from 0 to size-1.
So instead of using less-than-or-equal:
for (int a = 0; a <= arraySize; a++)
You should use less-than:
for (int a = 0; a < arraySize; a++)
The array size is declared to be 6 elements and then 7 elements [0...6] are placed in it.
Redeclare array size to be 7 and then change all the <= to < in the loops.