I want to ask how can I print the word Chessmaster in 2d array randomly each letter of the word? I tried with srand but I don't how to combine it with characters. Can someone help me with is code. Also, can I create random letters in a 2d array without rand ?
#include <iostream>
#include <stdlib.h>
#include <time.h>
const int MAX = 11;
using namespace std;
void printwo()
{
char word[MAX] = {'c', 'h', 'e', 's', 's', 'm', 'a', 's', 't', 'e', 'r'};
int c, i, n, letters;
cout << "I will print this word " << word << " sepereate" << endl;
srand(time(NULL));
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[i] << "]"
<< "["
<< "]";
cout << endl;
}
}
}
int main()
{
int c;
cout << "Hello user press _1_ to continue" << endl;
cin >> c;
if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
exit(0);
}
return 0;
}
#include <iostream>
#include <stdlib.h>
#include <time.h>
const int MAX = 11;
using namespace std;
// Generate a random number between min and max (inclusive)
// Assumes std::srand() has already been called
// Assumes max - min <= RAND_MAX
int getRandomNumber(int min, int max)
{
static constexpr double fraction { 1.0 / (RAND_MAX + 1.0) }; // static used for efficiency, so we only calculate this value once
// evenly distribute the random number across our range
return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}
void printwo()
{
char word[MAX+1] = {"chessmaster"}; //If you are using C-style strings then you should declare +1 space
//int c, i, n, letters; not needed
cout << "I will print this word " << word << " sepereate" << endl;
//srand only gives a seed to yout tand function, you need to call std::rand() to get a random integer
//use the function getRandomNumber above that is based on rand() and gives you the possibility to select range
srand(time(NULL));
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[getRandomNumber(0,10)] << "]"
<< "["
<< "]";
cout << endl;
}
}
}
int main()
{
int c;
cout << "Hello user press _1_ to continue" << endl;
cin >> c;
if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
//exit(0); exit here not needed
}
return 0;
}
I wrote some comments.. please read them and ask me if you don't get something. I would suggest reading about C-style strings and rand() here:
Rand() - https://www.learncpp.com/cpp-tutorial/59-random-number-generation/
C-style strings(basically arrays of char) - https://www.learncpp.com/cpp-tutorial/66-c-style-strings/
Related
This question already has answers here:
Segmentation fault while accessing vector elements
(2 answers)
Closed 26 days ago.
I currently have an assignment to make a board game in C++. I'm currently facing a problem with vectors because it keeps giving me 'Segmentation fault'. I have put an arrow comment at the part of my code which I think is the problem, It is in the Map::DisplayMap() function. But, I do not know what to do to fix it.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
struct Map
{
vector<vector<char>> board;
int DimX, DimY;
void CellContent(int DimX, int DimY);
void DisplayMap();
int getDimensions();
};
void Map::CellContent(int DimX, int DimY)
{
char objects[] = {' ', ' ', ' ', ' ', ' ', ' ', 'X', '#', '#', '$'};
int noOfObjects = 10;
board.resize(DimY); // Create empty vector
for (int i = 0; i < DimY; ++i)
{
board[i].resize(DimX);
}
for (int i = 0; i < DimY; ++i) // put random Characters inside vector
{
for (int j = 0; j < DimX; ++j)
{
int ObjectNumber = rand() % noOfObjects;
board[i][j] = objects[ObjectNumber];
}
}
}
void Map::DisplayMap()
{
cout << " --__--__--__--__--__--__--__--" << endl; // Header
cout << " = Alien, defeat the Zombies! =" << endl;
cout << " __--__--__--__--__--__--__--__" << endl;
// Each Row
for (int i = 0; i < DimY; ++i)
{
// DisplayMap upper border
cout << " ";
for (int j = 0; j < DimX; ++j)
{
cout << "+-";
}
cout << "+" << endl;
// DisplayMap row number
cout << setw(2) << (DimY - i);
// DisplayMap cell content
for (int j = 0; j < DimX; ++j)
{
cout << "|" << board[i][j];// <========= The problem starts here, I think.
// << " "; // letak content
}
cout << "|" << endl;
}
// DisplayMap lower border
cout << " ";
for (int j = 0; j < DimX; ++j)
{
cout << "+-";
}
cout << "+" << endl;
// DisplayMap column number
cout << " ";
for (int i = 1; i <= DimX; ++i)
{
int digit;
digit = i / 10;
if (DimX >= 10)
{
cout << " ";
if (digit == 0)
{
cout << " ";
}
else
{
cout << digit;
}
}
}
if (DimX >= 10)
{
cout << endl
<< " ";
for (int j = 1; j <= DimX; ++j)
{
cout << " " << (j % 10);
}
}
else
{
for (int j = 1; j <= DimX; ++j)
{
cout << " " << (j % 10);
}
}
}
int main()
{
Map Map;
Map.DimX = 11;
Map.DimY = 5;
Map.DisplayMap();
}
From what I learned, Segmentation faults happen when I try to access something I'm not supposed to. I don't know what it really means and how that happens in my code.
You are not calling CellContent() on your Map object to allocate and fill its board with data before then calling DisplayMap() to display the data, so its board is empty and your loops inside of DisplayMap() are exceeding board's bounds, hence the segfault.
int main()
{
Map Map;
Map.DimX = 11;
Map.DimY = 5;
Map.CellContent(11, 5); // <-- add this!
Map.DisplayMap();
}
That being said, it seems to me that CellContent() would be better off being a constructor instead, eg:
class Map
{
vector<vector<char>> board;
int DimX, DimY;
public:
Map(int DimX, DimY);
void DisplayMap() const;
int getDimensions() const;
};
Map::Map(int DimX, int DimY)
: DimX(DimX), DimY(DimY)
{
// prepare board as needed...
}
void Map::DisplayMap() const
{
// print board as needed...
}
int main()
{
Map map(11, 5);
map.DisplayMap();
}
So I have been having an extremely hard time trying to figure out this issue. All of my code currently works except for my last module where I am trying to compare the two arrays for differences and record the question number into a new array. I'm not really sure how to set it up. Any help will be appreciated.
The main issue is with the array incorrect I am creating. I do not know how to set up a blank array that gets bigger as values are entered. Unless I am just really messing that concept up. I have the issues currently commented out while I was trying different things.
#include <iostream>
using namespace std;
const int COLS = 20;
void input_data(char [], int);
void compare_data(char [], int, char [], int);
int main()
{
char letters[COLS];
char answers[] = { 'A', 'D', 'B', 'B',
'C', 'B', 'A', 'B',
'C', 'D', 'A', 'C',
'D', 'B', 'D', 'C',
'C', 'A', 'D', 'B'};
input_data(letters, COLS);
compare_data(letters, COLS, answers, COLS);
}
void input_data(char letter[], int size)
{
cout << "Please enter the student's answers for each of the questions. \n";
cout << "Press Enter after typing each answer. \n";
cout << "Please enter only an A, B, C, or D for each question. \n";
for (int i = 1; i <= size; i++)
{
cout << "Question " << i << ": ";
cin >> letter[i - 1];
while (letter[i - 1] != 'A' &&
letter[i - 1] != 'B' &&
letter[i - 1] != 'C' &&
letter[i - 1] != 'D')
{
cout << "Please enter only A, B, C, or D \n";
cout << "Question " << i << ":";
cin >> letter[i - 1];
}
}
}
void compare_data(char letter[], int size, char answer[], int cols)
{
int ans_correct = 0;
int ans_wrong = 0;
//int incorrect[20];
for (int i = 1; i <= size; i++)
{
if (letter[i] == answer[i])
ans_correct += 1;
else
{
ans_wrong += 1;
//incorrect[i-1] = i;
}
}
if (ans_correct >= 15)
cout << "The student passed the exam. \n";
else
cout << "The student did not pass the exam. \n";
cout << "Correct Answers: " << ans_correct << endl;
cout << "Incorrect Answers: " << ans_wrong << endl << endl;
cout << "Questions that were answered incorrectly: \n";
for (int i = 1; i < size; i++)
{
//cout << incorrect[i-1] << endl;
}
}
Ok, here is a working version. It does not grow the incorrect array, since that would be overkill for such a small operation, and you are using a constant 'COLS' anyhow.
Since it is a c++ tagged question, if you really want a dynamic array, why not use std::vector? You can do similar things with C-style arrays, but it is very messy.
void compare_data(char letter[], int size, char answer[], int cols)
{
int ans_correct = 0;
int ans_wrong = 0;
//setup array big enough to hold all answers
//and initialize to 0
int incorrect[COLS] = {0};
// Your original code had wrong loop limits!
for (int i = 0; i < size; i++)
{
if (letter[i] == answer[i])
ans_correct += 1;
else
{
//Fill in incorrect only on wrong answers!
//But the number you want to record is the
//the number of the question, which is i + 1
incorrect[ans_wrong] = i + 1;
ans_wrong += 1;
}
}
if (ans_correct >= COLS/2)
cout << "The student passed the exam. \n";
else
cout << "The student did not pass the exam. \n";
cout << "Correct Answers: " << ans_correct << endl;
cout << "Incorrect Answers: " << ans_wrong << endl << endl;
cout << "Questions that were answered incorrectly: \n";
//Even if the array is bigger, you don't wnat to output the
//unused parts
for (int i = 0; i < ans_wrong; i++)
{
cout << incorrect[i] << endl;
}
}
I'm trying to make a program that asks the user to input a string then checks to see how many vowels and consonants are in the string, using c strings. Right now I'm working on the function that counts the vowels. I finally got it to were I don't have any errors, but my program just hangs up after choosing to count the vowels. Here is my code.
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;
class VowelsandConsonants {
public:
int findVowels(char *cString, const int STRINGLEN) {
const int SIZE = STRINGLEN;
int vowelCount = 0;
char *str = cString;
char vowels[5] = { 'a', 'e', 'i', 'o', 'u' };
for (int i = 0; i < SIZE; i++) {
str[i];
for (int j = 0; j < SIZE; i++) {
vowels[j];
if (strcmp(vowels, str)) {
vowelCount++;
}
}
}
return vowelCount;
}
};
int main()
{
char *myString = nullptr;
const int STRLEN = 20;
int selection;
myString = new char[STRLEN];
VowelsandConsonants v;
cout << "Enter a string 20 characters or less." << endl;
cin.getline(myString, STRLEN);
cout << "Select the number of what you want to do." << endl;
cout << "1.) Count the number of vowels." << endl;
cout << "2.) Count the number of consonants." << endl;
cout << "3.) Count both vowels and consonants." << endl;
cout << "4.) Enter another string." << endl;
cout << "5.) Exit program." << endl;
cin >> selection;
if (selection == 1) {
cout << v.findVowels(myString, STRLEN);
}
delete[] myString;
return 0;
}
Am I approaching this the right way?
I recommend using a C-Style string containing the vowels, then using strchr to search it:
const char vowels[] = "aeiou";
const size_t length = strlen(cString);
unsigned int vowel_count = 0;
for (unsigned int i = 0; i < length; ++i)
{
if (strchr(vowels, cString[i]) != NULL)
{
++vowel_count;
}
}
There are other methods, such as using an array to hold the counts (and using the letter as an index) or std::map.
I'm used to java, and struggle with basic syntax of C++ despite knowing theory. I have a function that is trying to count the number of occurrences in a string, but the output is a tab bit weird.
Here is my code:
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
main
* Start
* prompt user to enter string
* call function
* stop
*
* count
* start
* loop chars
* count charts
* print result
* stop
*/
using namespace std;
void count(const char s[], int counts[]);
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
Here is the output:
Enter a string: Dylan
You entered Dylan
b: 1Times
c: 1Times
d: 2Times
f: 1Times
h: 1Times
i: 1229148993Times
j: 73Times
l: 2Times
n: 2Times
p: 1Times
r: 1Times
v: 1Times
Any help you can give me would be greatly appreciated. Even though this is simple stuff, I'm a java sucker. -_-
Your counts is uninitialized. You need to first set all of the elements to 0.
You need to zeros the counts vector.
Try
counts[26]={0};
I don't know about java, but you have to initialize your variables in C/C++. Here is your code working:
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
for(int i=0; i<26; i++)
counts[i]=0;
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}
I don't understand why this program is not working.
I need to find the number of occurrences of all characters in three strings by any method.
I used count method but if you guys can help me out with find function so it would be better.
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string line[3];
int count[3];
cout << "Enter three lines of text...\n\n";
cin >> line[0];
cin >> line[1];
cin >> line[2];
int i;
for(char j='a'; j<=26; j++) {
for(i=0; i<3; i++)
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
}
system ("pause");
return 0;
}
26 is no letter, and (char)26 is normally less than 'a' - so your loop will not execute. Try char j='a';j<='z';j++
I would go for something like this:
#include <map>
#include <string>
#include <iostream>
int main()
{
// Given 3 strings...
std::string s1 = "Hello";
std::string s2 = "Cruel";
std::string s3 = "World";
//===============================================
// THESE 2 LINES ARE ALL YOU NEED FOR COUNTING
std::map<char, int> countMap;
for (char c : (s1 + s2 + s3)) { countMap[c]++; }
//===============================================
// Print the output. This is if you do not care about
// characters that do not appear at all.
for (auto const& e : countMap)
{
std::cout << e.first << ": " << e.second << std::endl;
}
// Print the output. This is if you DO care about
// characters that do not appear at all.
for (char c = ' '; c <= '~'; c++)
{
std::cout << c << ": " << countMap[c] << std::endl;
}
}
http://www.asciitable.com/
Lower case 'a' is 96. Which is less than 26 which is why your loop doesn't execute. Try:
for (char j = 'a'; j <= 'z'; j++)
This will only count the lower case characters. If you wanted the occurrence of lower and upper case you could do this:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string line[3];
cout << "Enter three lines of text...\n\n";
cin >> line[0];
cin >> line[1];
cin >> line[2];
for(char j='a';j<='z';j++)
{
int upper_sum = 0;
int lower_sum = 0;
for(int i=0;i<3;i++)
{
lower_sum += std::count(line[i].begin(),line[i].end(),j);
upper_sum += std::count(line[i].begin(),line[i].end(),j - 32); //32 = 'a' - 'A'
}
cout<<"\n"<<j<<"\t"<<":"<<"\t"<<lower_sum;
cout<<"\n"<<(char)(j - 32)<<"\t"<<":"<<"\t"<<upper_sum;
}
return 0;
}
Here's a correct version of your program:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string line[3];
int count[3];
/*cout<<"Enter three lines of text...\n\n";
cin>>line[0];
cin>>line[1];
cin>>line[2];*/
line[0] = "aaaaabbbbbbbbbbb";
line[1] = "ccccccddddddddddd";
line[2] = "kkkkkkkkkkkkk";
int i;
for(char j='a';j<= 'z';j++) // You can loop through the alphabet, but you need to go 'a' to 'z' and not 26
{
for(i=0;i<3;i++)
{ // You were missing these braces, you need them if your loop contains multiple lines
count[i]= std::count(line[i].begin(),line[i].end(),j);
cout<<"\n"<<j<<"\t"<<":"<<"\t"<<count[i];
}
}
system ("pause");
return 0;
}
And here it is in action.
int i;
for(char j='a'; j<=26; j++) {
for(i=0; i<3; i++)
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
}
Your cout line isn't in the inner for loop.
After the inner loop finishes, i is 3. Then cout is called with count[i] which goes out of bounds on the array. Undefined behaviour, you're lucky if it crashes.
Your problem is the i. The place it's declared means it still exists and the cout line can reference it. If you move the declaration to the loop initialiser you'll find the next error:
for(int i=0; i<3; i++)
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
The last line won't compile as i goes out of scope at the end of the loop. I assume you were mistaken in thinking cout was part of the loop, partly due to the poor formatting of the code, and secondly because i was declared at a wider scope.
To correct this, create a block for the for loop by using { and }. This will keep the i in scope for all statements within the block, and repeat the statements for each iteration of the loop.
for(int i=0; i<3; i++) {
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
}