I've been learning C++ for only a couple of months. We had a project that was due about pointers/reference. This is my code below that I submitted. However, My teacher said I didn't include pointers/references in my code. I was certain that I did on line 31-42. I'm having trouble understanding pointers. Please give feedback on what I should do differently.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
//Opening File
ifstream cafefile;
cafefile.open("cafeteria.txt");
//Check for errors
if (!cafefile)
{
cout << "cafeteria.txt did not open properly" << endl;
exit(9999);
}
//String & char
string choice;
string array[4][3];
char out;
//Pointers to the food
string food[] { "Cheese Pizza", "Hamburger", "Fish Sticks", "Mystery Meat" };
string *foodptr {food};
//Set yes & no to 4 array
int yes[4]{ 0 };
int no[4]{ 0 };
//pointer for integer Yes / NO
int* yesptr{ yes };
int* noptr{ no };
//Counters of Likes & Dislikes set = 0
int like = {0};
int dislike = {0};
for (int i = 0; i < 4; i++)
{
//Reopen the file
ifstream file("cafeteria.txt");
while (getline(file, choice))
{
istringstream pick(choice); //istringstream is input stream class, which operates on string
getline(pick, choice, '\t');
if (foodptr[i] == choice)
{
pick >> choice;
if (choice == "Y")
like++; //increment
else if (choice == "N")
dislike++; //increment
}
}
//Setting the yes = like
yesptr[i] = like;
noptr[i] = dislike;
//Set to 0
like = 0;
dislike = 0;
}
for (int m = 0; m < 4; m++)
{
array[m][0] = foodptr[m];
}
for (int j = 0; j < 4; j++)
{
array[j][1] = to_string(yesptr[j]);
}
for (int i = 0; i < 4; i++)
{
array[i][2] = to_string(noptr[i]);
}
//Display of the Program
cout << "School Cafeteria Survey!" << endl;
cout << endl;
cout << "Food Item" << "\t" << "Like" << "\t" << "Dislike" << endl; //Gives the tab space Horizontally in your output
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
cout << array[i][j] << "\t";
}
cout << endl;
}
//Background color, making it unique
system("color 6");
//Exit the Prgram
cout << endl;
cout << "Please enter 'E' to exit!";
cin >> out;
if (out == 'e' || out == 'E')
{
exit(0);
}
system("pause"); //pause the program
return 0;
}
Please provide solutions on what I should fix.
It would be better if you create your arrays dynamically i.e. make the 2D array dynamically using pointers
string **array;
array = new int *[4];
for(int i=0; i<4; i++){
array[i] = new int[3];
}
Other than this, your teacher must have wanted your to access these array not using indexing, but rather by using pointers and references. This means that you shouldn't access arrays using yesptr[i] but rather by using *(yesptr + i).
So for e.g. if you are in a loop do the following
for (int m = 0; m < 4; m++)
{
*(*(array+m)+0) = *(foodptr+m);
}
Related
I'm trying to create a program where you input 20 characters into an array. Each time you enter a new character, the program should check if that character is already in the array, if it is, print duplicate (but still add the duplicate to the array)
For example, if user types 'a', program should check if 'a' is inside the array.
This is my code:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i= 0; i <= 20; i++) {
cin >> input;
for (int k = 0; k <= 20; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
myAlpha[i] = input;
}
}
I just can't figure out how to make it work, I'm probably missing something stupid. The solution must use something like the code above, no fancy functions or anything.
EDIT: Fixed Code:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i= 0; i < 20; i++) {
cin >> input;
for (int k = 0; k < i; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
myAlpha[i] = input;
}
}
Only problem is that "duplicate" is printed a extra time for each duplication of a letter. For example, if 'a' is entered 3 times, on the 3rd time, "duplicate" is printed 2 times. And so on. But not a big deal.
try this:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i = 0; i < 20; i++) {
cin >> input;
myAlpha[i] = input;
for (int k = 0; k < i; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
}
}
With this line:
char myAlpha[20];
The valid indices of that array are from 0 to 19. However, this line:
for (int i= 0; i <= 20; i++) {
Already implies a bug. Change it to this:
for (int i= 0; i < 20; i++) {
Do the same treatment for the inner for loop line: for (int k = 0; k <= 20; k++) {
But... you'll also need to keep track of how many characters have been inserted instead of looping up to 20 again.
So this is closer to what you want:
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
int inserted = 0;
while (inserted < 20) {
cin >> input;
bool duplicate = false;
for (int k = 0; k < inserted; k++) {
if (myAlpha[k] == input) {
cout << "Duplicate" << endl;
duplicate = true;
break; // no point in continuing to look for duplicates once the first one is found
}
}
if (!duplicate) {
myAlpha[inserted] = input;
inserted++;
}
}
}
Even faster and you can avoid the inner for-loop:
int main() {
bool duplicates[256] = {};
char myAlpha[20] = {};
char input;
cout << "Enter a letter" << endl;
int inserted = 0;
while (inserted < 20) {
cin >> input;
bool duplicate = duplicates[(unsigned char)input];
if (duplicate) {
cout << "Duplicate" << endl;
}
else {
myAlpha[inserted] = input;
inserted++;
duplicates[(unsigned char)input] = true;
}
}
}
I am stuck on what to do next... The program is suppose to check to see if entered Zero-One Matrix is an Equivalence relation (transitive, symmetric, and reflexive) or not. I am still new to C++ (started this semester). I know how to create the matrix using vector but not on how to check if it is equivalence relation or not..
I assume I need to use boolean function but I'm stuck on what I need to put in as an argument or if this is correct. My original thought was... so for symmetric it will look like (which I know this goes after #include and beofre int main(). Any help would be awesome.
bool isSymmetric(vector<int> &vect, int Value)
{
for (int i = 0; i < Value; i++)
for (int j = 0; j < Value; j++)
if (vect[i][j] != vect[j][i])
return false;
return true;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > vec;
cout << "NxN matrix N: ";
int Value;
cin >> Value;
cout << Value << "x" << Value << " matrix\n";
for (int i = 0; i < Value; i++) {
vector<int> row;
for (int j = 0; j < Value; j++) {
cout << "Enter a number (0 or 1): ";
int User_num;
cin >> User_num;
while (User_num != 0 && User_num != 1) {
cout << "Invalid Entry! Enter 0 or 1!\n";
cout << "Enter a number (0 or 1): ";
cin >> User_num;
}
row.push_back(User_num);
}
vec.push_back(row);
}
cout << endl;
for (int i = 0; i < Value; i++) {
for (int j = 0; j < Value; j++) {
cout << vec[i][j] << " ";
}
cout << endl;
}
cout << endl;
system("pause");
return 0;
}
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 !";
}
So I've been working on a project for class and everything was going swimmingly, until I had to sort the information by last name in ascending order. To elaborate further, in my program I am supposed to take file input, apply it into whatever kind of variables I see fit, calculate their grades by comparing their answers against an answer key, and then sort the entries by last name. Without further ado here is my code! (be gentle)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <algorithm>
const int TEST_SIZE = 10;
using namespace std;
struct StudentInfo
{
int id;
string fName;
string lName;
char testAnswers[10];
int totalPoints = 0;
int avg = 0;
char letterGrade;
};
void inputInfo(char[], StudentInfo[]);
void calcGrade(char[], StudentInfo[]);
void bubbleSort(StudentInfo[]);
void outputInfo(StudentInfo[]);
int main()
{
StudentInfo studentInfo[10];
string temp;
char answerKey[10];
inputInfo(answerKey, studentInfo);
calcGrade(answerKey, studentInfo);
bubbleSort(studentInfo);
outputInfo(studentInfo);
return 0;
}
void inputInfo(char answerKey[], StudentInfo studentInfo[])
{
cout << "Please enter the 10-question answer key: \n";
for(int i = 0; i < TEST_SIZE; i++)
{
cout << "Question " << i+1 << "\n";
cin >> answerKey[i];
}
ifstream inFile("student.txt");
for(int i = 0; i < TEST_SIZE; i++)
{
inFile >> studentInfo[i].id;
inFile >> studentInfo[i].fName;
inFile >> studentInfo[i].lName;
for(int j = 0; j < TEST_SIZE; j++){
inFile >> studentInfo[i].testAnswers[j];
}
}
}
void calcGrade(char answerKey[], StudentInfo studentInfo[])
{
for(int i = 0; i < TEST_SIZE; i++)
{
for(int j = 0; j < TEST_SIZE; j++)
{
if(studentInfo[i].testAnswers[j] == answerKey[j])
{
studentInfo[i].totalPoints += 5;
}
studentInfo[i].avg = studentInfo[i].totalPoints * 2;
if(studentInfo[i].avg >= 90)
{
studentInfo[i].letterGrade = 'A';
}
else if(studentInfo[i].avg >= 80)
{
studentInfo[i].letterGrade = 'B';
}
else if(studentInfo[i].avg >= 70)
{
studentInfo[i].letterGrade = 'C';
}
else if(studentInfo[i].avg >= 60)
{
studentInfo[i].letterGrade = 'D';
}
else
{
studentInfo[i].letterGrade = 'F';
}
}
}
}
void bubbleSort(StudentInfo studentInfo[])
{
StudentInfo temp;
int i;
int j;
for(i = 0; i < (TEST_SIZE-1); i++)
{
for(j = 0; j < TEST_SIZE; j++)
{
if(studentInfo[j].lName < studentInfo[j-1].lName)
{
temp = studentInfo[j];
studentInfo[j] = studentInfo[j-1];
studentInfo[j-1] = temp;
}
}
}
}
void outputInfo(StudentInfo studentInfo[])
{
cout << setprecision(1) << fixed;
cout << "Student ID\tStudent Name\tAnswers\tTotal Pts\tAverage\t Letter Grade" << endl;
for(int i = 0; i < TEST_SIZE; i++)
{
cout << studentInfo[i].id << "\t";
cout << studentInfo[i].lName << " ";
cout << studentInfo[i].fName << "\t";
for(int j = 0; j < TEST_SIZE; j++)
{
cout << studentInfo[i].testAnswers[j];
}
cout << "\t" << studentInfo[i].totalPoints << "\t";
cout << studentInfo[i].avg << "\t";
cout << studentInfo[i].letterGrade << "\n";
}
}
I've tried everything within my meager abilities, but my program always crashes. Assumedly during the bubble sort since it works fine without that section. If someone could enlighten me as to where I erred I would be very grateful. Sorry for any inconvenience that I've caused.
What happens here
temp = studentInfo[j];
studentInfo[j] = studentInfo[j-1];
studentInfo[j-1] = temp;
when j==0? You access out of bounds. You're better off using std::swap from <algorithm> like
std::swap(studentInfo[j], studentInfo[j+1]);
making sure that you run j until TEST_SIZE - 1. Or write the "manual" swap but with j exchanged by j+1.
Hi guys I am trying to make a program that takes some user input and maps it to a 2d array and then encrypts it by mixing up the columns. For example if the user enters "my name is fred" the program creates an array that is 3x6 filling the last column with y's and the remain empty spaces with x's so it should be something like
mynamy
eisfry
edxxxx
instead I wind up with
mynam
eisfr
edxx
#include <iostream>
#include<cctype>
#include<algorithm>
using namespace std;
main(){
string input;
cout << "Enter information to be encrypted" << endl;
getline(cin,input);
input.erase(std::remove (input.begin(), input.end(), ' '), input.end());
int columns = 6;
int rows;
if (input.size() <= 5){
rows = 1;
}
else if (input.size()% 5 > 0){
rows = input.size()/5 + 1;
}
else
rows = input.size()/5;
char message[rows][columns];
int place = 0;
for(int i = 0; i < rows; i++){
for(int j = 0; j < (columns-1); j++){
if(place <= input.size()){
message[rows][columns] = input[place];
}
else {
message[rows][columns] = 'x';
}
place++;
message[rows][5] = 'y';
cout << message[rows][columns];
}
cout << endl;
}
}
this should do it..
#include <iostream>
#include <cctype>
#include <algorithm>
using namespace std;
int main()
{
string input;
cout << "Enter information to be encrypted" << endl;
getline(cin,input);
input.erase(std::remove (input.begin(), input.end(), ' '), input.end());
int columns = 6;
int rows;
if (input.size() <= 5){
rows = 1;
}
else if (input.size()% 5 > 0){
rows = input.size()/5 + 1;
}
else
rows = input.size()/5;
char message[rows][columns];
for(int i = 0; i < rows; i++){
for(int j = 0; j < (columns-1); j++){
if ((i*5 + j) < int(input.size())){
message[i][j] = input[i*5 + j];
}
else {
message[i][j] = 'x';
}
// place++;
if (i != rows-1) message[i][5] = 'y';
else message[i][5] = 'x';
// cout << "i: " << i << " | j: " << j << " | " << message[i][j] << endl;
}
cout << endl;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << message[i][j];
}
cout << " ";
}
cout << endl;
}
Your code isn't actually doing anything to transpose the matrix! It's writing the message into the matrix, but it's printing each entry out right after it's written, so it doesn't end up changing the order at all.
You'll need a separate set of loops to read data out of the matrix.