I'm reading in a sodoku board from a text file. The board is represented by 9 rows of 9 digit numbers, like this:
594632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
EDIT
Here are the results when I change the while condition to (input >> char):
Output as chars are read in:
96212486
71931369
48728254
35185947
67350
Output of printArray:
962124867
193136948
728254351
859476735
�$%w��
����QȿȔ
L�`g�Pw
���w�
And here's the output for while (!input.eof()):
�94632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
END EDIT
The trouble is, when I place each digit into a multidimensional array, the element at [0][0] appears as a shaded question mark (compiled with g++). The problem only surfaces when I'm printing out the contents of the array, the data as it's read in appears to be fine. For what it's work, this also happens if I cout << board[0][0] from the main function.
Any help would be appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int createArray(string filename);
bool checkRows(char board[][9]);
bool checkColumns(char board[][9]);
bool checkBoxes(char board[][9]);
void printArray(char board[][9]);
int main ()
{
char board [9][9];
int i = 0;
int j = 0;
int count = 0;
ifstream input("board.txt");
char ch;
while (input >> ch)
{
// ch = input.get();
if (ch != '\n')
{
cout << ch;
board[i][j] = ch;
j++;
if (j % 9 == 0)
{
i++;
}
}
if (j > 8)
j = 0;
if (i > 8)
i = 0;
count++;
if (count % 10 == 0)
cout << endl;
}
input.close();
printArray(board);
cout << checkRows(board) << endl;
cout << checkColumns(board) << endl;
return 0;
}
void printArray(char board[][9])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << board[i][j];
}
cout << endl;
}
cout << board[0][0] << endl;
cout << board[0][1] << endl;
}
By doing this, reading ch two times.
Remove ch = input.get(); and you will read each number correctly.
while (input >> ch)
{
ch = input.get();
...
}
Again, consider changing condition below to make sure correct endl placement
if (count % 10 == 0)
cout << endl;
to
if (count % 9 == 0)
cout << endl;
Related
This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}
#include <iostream>
using namespace std;
int main ()
{
int A[20], i, k;
cout << "Write 20 random numbers: "<<endl;
for(i=0; i<20; i++){
cout << "A[" << i << "]: ";
cin >> A[i];
}
k=0;
if (i+1 == k){
cout << "The program has two consecutive zeros";
}
else if (i+1 != k){
cout << "The program doesn't own two consecutive zeros";
}
char ch1;
cin>>ch1;
return 0;
}
This is my code but I don't know how to configure out the if to show me a message first, if there are two zeros, and second if there aren't. If there are, I need to make it so the numbers on which these zeros are shown. I'm a student please help, I really have no idea how to do it
I did it for the most part. Thank you everyone for your help! What's left now is to make it so it shows to which respective numbers the zeros are. How do I do that? I did as varleti suggested but it only shows 20 and 21
You already have a loop that you use to collect the data.
cout << "Write 20 random numbers: "<< endl;
for(i=0; i<20; i++) {
cout << "A[" << i << "]: ";
cin >> A[i];
}
You have collected the data into a 20 element array A[20].
You need to walk through the array again and test the values for 2 consecutive zeros.
two_zeros = 0;
for(i=1; i<20; i++) { // Note, starting from element [1]
if( A[i] == 0 && A[i-1] == 0 ) { // Test this and previous element for zeroness
two_zeros = 1;
}
}
if( two_zeros == 1 ) {
cout << "The program has two consecutive zeros";
} else {
cout << "The program doesn't own two consecutive zeros";
}
See this code snippet:
#include <iostream>
using namespace std;
int main ()
{
int A[20], i, k;
cout << "Write 20 random numbers: "<<endl;
for(i=0; i<20; i++){
cout << "A[" << i << "]: ";
cin >> A[i];
}
int count = 0; /* To count number of consecutive zeroes */
int flag = false; /* check wheather consecutive zeroes are found or not */
for(i=0; i<20; i++) {
if(A[i] == 0) {
count++;
if(count == 2) {
flag = true;
cout << "The program has two consecutive zeros" << endl;
break;
}
} else {
count = 0;
}
}
if(flag == false) {
cout << "The program doesn't own two consecutive zeros";
}
return 0;
}
Let me know, if having any doubt regarding anything.
You don't need any array, you only need to remember whether the last number you read was zero.
int main ()
{
bool last_zero = false;
bool two_zeros = false;
cout << "Write 20 random numbers: "<<endl;
for(int i = 0; i < 20; i++){
int x = 0;
cin >> x;
if (x == 0)
{
if (last_zero)
{
two_zeros = true;
}
last_zero = true;
}
else
{
last_zero = false;
}
}
if (two_zeros){
cout << "The program has two consecutive zeros";
}
else {
cout << "The program doesn't own two consecutive zeros";
}
}
#include <iostream>
using namespace std;
int main ()
{
int A[20], i, k=0;
cout << "Write 20 random numbers: "<<endl;
cout << "A[0]";
cin >> A[0];
for(i=1; i<20; i++)
{
cout << "A[" << i << "]: ";
cin >> A[i];
if( A[i] == 0 && A[i-1] == 0 )
{
cout << "The program has two consecutive zeros";
k=1;
break;
}
}
if(k==0)
cout << "The program hasn't two consecutive zeros";
return 0;
}
int count = 0;
for (int j = 0; j<20 - 1; j++)
{
if (arr[j] == 0 && arr[j + 1] == 0)
{
count++;
break;
}
}
if (count == 1)
{
cout << found;
}
else
cout << not found;
I would like to to print a triangle with a given letter. For example, if I input D, the program should return:
A
AB
ABC
ABCD
So far, I have managed to print all letters until the given one in my example, but as you see this method is not quite effective since I need to do this for all 26 cases since the English alphabet is 26 chars. Is there some way to optimize my code?
#include <iostream>
using namespace std;
int main() {
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
if (65 < c) {
cout << "A";
cout << endl;
}
if (66 < c) {
cout << "AB";
cout << endl;
}
if (67 < c) {
cout << "ABC";
cout << endl;
}
for (int i = 64; i < c; i++) {
cout << static_cast<char>(i + 1);
}
return 0;
}
You definitely need to work on your comprehension of loops. This one works just fine and it even has some checks on what is typed in and it eventually converts lower case letters into upper casse.
char first = 'A';
char last = 0;
cout << "Enter a char: ";
cin >> last;
fflush(stdin);
cout << "\n\n";
if ((last > 96) && (last < 123)) //97 to 122 are lower case letters
{
last -= 32; //32 is the delta between each lower case letter and its upper case "twin"
}
if ((last > 64) && (last < 91))
{
for (char i = 65; i <= last; i++)
{
for (char j = 65; j <= i; j++)
{
cout << j;
}
cout << "\n";
}
}
else
{
cout << "\nWrong character!!\n\n";
return 0;
}
Use a nested loop structure. Use the outer loop to 'walk' down your triangle,
lineLength = 1;
while(lineLength <= (c - 64)){
...stuff...
lineLength++;
cout << endl;
}
Use the inner loop to 'walk' down the alphabet (you've already done most of this):
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
Putting it together:
lineLength = 1;
while(lineLength <= (c - 64)){
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
lineLength++;
cout << endl;
}
I see that someone else has posted a similar answer. Between these two answers, you should be able to find your way. I haven't compiled and run this code, but I believe that it should work or be very close.
Don't harcode ascii integer values into code. Explicitly use the character or string literals (e.g. 'A' instead of 65)
Start with a helper function to print exactly one line
// prints all the characters of the alphabetic sequence from "A" to the final char designated by <c>
void printTriangleLine(char c)
{
if ((c < 'A') || (c > 'Z'))
{
return;
}
for (char x = 'A'; x <= c; x++)
{
cout << x;
}
cout << endl;
}
Then put it all together in your main:
int main()
{
char i;
cout << "Enter char ";
cin >> i;
if ((i < 'A') || (i > 'Z'))
{
return 0;
}
for (char x = 'A'; x <= i; x++)
{
printTriangleLine(x);
}
return 0;
}
We must run the loop from position is above 'A' character
until we reached the charanter you enter
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
in each loop we increment character value by 1 to go to the next value
// go to next letter
chNew++;
inner loop simply print the character from A to next value relative to current chNew + 1, it is because we also want to include current character to our printed line.
Here is your working code.
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
// start with 'A' - 1 character
char chNew = 'A' - 1;
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
// we have done
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAX_NUMS = 200; // Constant for the maximum number of words.
const int MAX_GUESSES = 8;
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";
char inputLetter();
int findChar(char letter, string&word);
string getGuessedWord(string&secretWord, string&lettersGuessed);
string getLettersGuessed(char letter, string&lettersGuessed, int n);
void display(string&lettersGuessed, string&wordGuessed, int num, int pos);
bool isDone(string wordGuessed);
int main()
{
string oneWord; // holds one word from input file
string secretWord; // holds secret word to be guessed
string words[MAX_NUMS]; // holds list of words from input file
int randomValue; // holds index of secret word
int count = 0; // holds number of words in the file
// Declare an ifstream object named myFile and open an input file
ifstream myFile;
myFile.open("P4Words.txt");
// Exit program if cannot open file for input
if (!myFile)
{
cout << "Error: Unable to open file for input" << endl;
return 0;
}
// Input words from a file into words array
// Add your code here ...
myFile >> oneWord;
while (!myFile.eof())
{
words[count] = oneWord;
count++;
myFile >> oneWord;
}
myFile.close();
cout << count << " words loaded." << endl;
srand(static_cast<unsigned int>(time(0)));
// Select a secret word
// Add your code here ...
secretWord = words[rand() % (count + 1) ];
// Possible useful variables the loop
string lettersGuessed = ""; // holds letters guessed so far
string wordGuessed; // holds current word guessed like �_ pp_ e�
int incorrectGuesses = 0; // holds number of incorrect guesses so far
char letter; // holds a guessed letter
bool done = false; // have not guessed the word yet
int num = 8; int pos;
cout << "Welcome to the game, Hangman V1 by Your Name!" << endl;
cout << "I am thinking of a word that is " << secretWord.length()
<< " letters long." << endl;
// Set up a loop to input guesses and process
// Add your code here ...
do
{
letter = inputLetter();
pos = findChar(letter, secretWord);
wordGuessed = letter;
lettersGuessed = getLettersGuessed(letter, lettersGuessed, 8 - num);
wordGuessed = getGuessedWord(secretWord, lettersGuessed);
display(lettersGuessed, wordGuessed, num, pos);
done = isDone(wordGuessed);
num--;
} while ((num > 1) && (done == false));
// Check for won or lost
// Add your code here ...
if (done == false)
{
cout << "sorry you lose..." << endl;
}
if (done == true)
{
cout << "congratulations! " << endl;
}
system("pause"); // stop program from closing, Windows OS only
return 0;
}
// Add function definitions here ...
char inputLetter()
{
int i;
char letter;
do
{
cout << "please guess a letter: " << endl;
cin >> letter;
for (i = 0; i < 25; i++)
{
if (letter == LETTERS[i])
{
return letter;
}
}
if (letter != LETTERS[i])
{
cout << "Oops! That is an invalid character." << endl;
}
} while (letter != LETTERS[i]);
}
int findChar(char letter, string &word)
{
int i = 0; int pos = 0; bool found = false;
do
{
if (word[pos] == letter)
{
return pos;
found = true;
}
pos++;
} while (pos<word.length() - 1);
if (found == false)
{
return -1;
}
}
string getGuessedWord(string&secretWord, string&letterGuessed)
{
string temp;
temp = secretWord;
for (size_t k = 0; k <= temp.length() - 1; k++)
{
temp[k] = '_';
}
for (size_t i = 0; i <= temp.length() - 1; i++)
{
for (size_t j = 0; j <= temp.length() - 1; j++)
{
if (letterGuessed[i] == secretWord[j])
{
temp[j] = letterGuessed[i];
}
}
}
return temp;
}
string getLettersGuessed(char letter, string&lettersGuessed, int n)
{
string temp;
temp = letter;
lettersGuessed.insert(n, temp);
return lettersGuessed;
}
void display(string&lettersGuessed, string&wordGuessed, int num, int pos)
{
if (pos != -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Good guess!: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
if (pos == -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Oops! that letter is not my word: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
}
bool isDone(string wordGuessed)
{
bool done = false; int k = 0;
for (size_t i = 0; i <= wordGuessed.length() - 1; i++)
{
if (wordGuessed[i] == '_')
{
k++;
}
}
if (k == 0)
{
done = true;
}
return done;
}
it says subscript is out of range I need help to fix it
let me know how to fix it please its a project that is due very soon
that's all I got so far
Change:
for (size_t i = 0; i <= temp.length() - 1; i++)
to:
for (size_t i = 0; i <= letterGuessed.length() - 1; i++)
I need help with getting this users input of an integer and retrieving the even numbers and displaying them with spaces.I already have the input processed into an array and have it reversed (thanks to stackoverflow) now need to extract the even numbers from the array and display them.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int evenNumbers(char even[], int num[], int indexing[]);
int main()
{
char integers[5];
int numbers[5];
int even[5] = {0,2,4,6,8};
int evens;
cout << "Please enter an integer and press <ENTER>: " << endl;
for (int j = 0; j < 5; j++)
cin >> integers[j];
for (int j = 0; j < 5; j++)
{
numbers[j]= integers[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << integers[j - 1] << " ";
}
cout << endl;
//having problems finding the even numbers and displaying the even numbers
//from the users input of integers, i have only learned how to display the
//subscript by a linear search
evens = evenNumbers(integers, numbers, even);
if (evens == -1)
cout << "There are no even numbers" << endl;
else
{
cout << "The even numbers are: " << (evens + 1) << endl;
}
system("pause");
return 0;
}
int evenNumbers(char even[], int num[], int indexing[])
{
int index = 0;
int position = -1;
bool found = false;
for (int j = 0; j < 5; j++)
{
num[j]= even[j] - '0';
}
while (index < 5)
{
if (num[index] == indexing[index])
{
found = true;
position = index;
}
index++;
}
return position;
}
If you want to display the even numbers from the array integers you can use a simple for loop and if statement:
for(int i = 4; i >= 0; i--)
{
if(integers[i] % 2 == 0)
cout << integers[i] << " ";
}
Your approach is all wrong, you can't detect even numbers by searching a list, you need a mathematical test for evenness. Write a function called is_even which tests one number and returns true if it is even and false if it is not. Then you can use that function, very simply, like this
for (int j = 0; j < 5; j++)
{
if (is_even(integers[j]))
cout << integers[j] << " ";
}
cout << endl;
Now you just need to write the is_even function.
void evennumbers(int num[])
{
for(int i=0;i<5;i++)
{
if(num[i]%2==0)
cout<<num[i]<<" ";
}
}
And avoid taking input to char what if user enters a number with more than one digit
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void validNum(char valid[]);
void reverseNum(char rev[], int num2[]);
void evenNumbers(char even[], int num3[]);
void oddNumbers(char odd[], int num4[]);
int main()
{
char integer[5];
int number[5];
cout << "Your number is: ";
validNum(integer);
cout << "Your number in reverse is: ";
reverseNum(integer, number);
cout << "Even numbers: ";
evenNumbers(integer, number);
cout << endl;
cout << "Odd numbers: ";
oddNumbers(integer, number);
cout << endl;
system("pause");
return 0;
}
void validNum(char valid[])
{
char ch;
cout << "Please enter an integer and press <ENTER>: " << endl;
ch = cin.get;
while (ch < 0 || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
cout << "ERROR: Please enter a positive integer and press <ENTER>: ";
for (int i = 0; i < 5; i++)
cin >> valid[i];
}
for (int j = 0; j < 5; j++)
{
cout << valid[j] - '0';
}
}
void reverseNum(char rev[], int num2[])
{
for (int j = 0; j < 5; j++)
{
num2[j]= rev[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << rev[j - 1]<< " ";
}
cout << endl;
}
void evenNumbers(char even[], int num3[])
{
for (int i = 0; i < 5; i++)
{
if (even[i] % 2 == 0)
{
cout << num3[i] << " ";
}
}
}
void oddNumbers(char odd[], int num4[])
{
for (int i = 0; i < 5; i++)
{
if (odd[i] % 2 == 1)
{
cout << num4[i] << " ";
}
}
}