This is a program that is suppose to compare an answer sheet (which is a .txt file) to user input. Meaning I'm comparing two arrays but I'm having a PITA time making it work. It complies just fine but it just does not compare the user input array to the .txt file array and counts everything as wrong even when I manually put in the correct answers on the user input side. Any advice or suggestions would be appreciated! PS: I cannot use vectors, only arrays. That's not a personal choice but a requirement.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int CHOICE = 20;
const char KEY = 20;
char correctAnswers[KEY];
char A, B, C, D;
char userAnswers[CHOICE];
char rightOrWrong[CHOICE];
int totalMissed;
int sum = 0;
int count = 0;
ifstream inputFile;
inputFile.open("CorrectAnswers.txt");
while (count < KEY && inputFile >> correctAnswers[count])
count++;
inputFile.close();
for (int qst = 0; qst < 20; qst++)
{
cout << "Please put an answer for the question: " << endl;
cin >> userAnswers[qst];
cout << endl;
if (userAnswers[qst] == correctAnswers[qst])
{
rightOrWrong[qst] = 'C';
}
else
{
rightOrWrong[qst] = 'I';
}
}
for (int qst = 0; qst < 20; qst++)
{
if (rightOrWrong[qst] == 'C')
{
sum += 1;
}
else
{
cout << "Answer #" << qst << " is not correct" << endl;
}
}
totalMissed = 20 - sum;
cout << "This is your final score: " << endl;
cout << "You missed " << (20 - sum) << "/20 of the questions" << endl;
cout << "You overall percentage is " << (sum / 20) << "%." << endl;
if (sum < 14 && sum >= 0)
{
cout << "You have not passed the exam. You must have a 70% or higher to pass. Study harder next time!" << endl;
}
else
{
cout << "Pat yourself on the back! You've passed the test!" << endl;
}
return 0;
}
I apologize if this looks crappily formatted, it doesn't look like this normally.
Related
I am messing around with dynamic arrays for a user defined amount of inputs for an and gate.
The issue I am running into is that I don't know how many inputs the user is going to test and I need to be able to have an if-else statement that tests each input.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput = 0;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1 = 0;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
return 0;
}
Here is the code that I am currently trying to find a solution for.
To implement an AND gate with n inputs you can simply do:
int output = 1;
for (int i = 0; i < n; ++i)
{
if (!and_gate [i])
{
output = 0;
break;
}
}
// ...
Use Vector data structure, you don't need to tell its size while declaring, unlike array, and it can grow automatically.
To read input till it's arriving, put cin inside while loop condition. I used getline to read whole line and work with it, so that whenever user presses enter button at empty line, program will think that no more input is coming anymore, and will start calculating 'And' of inputs.
//don't forget to import vector
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
logic_gate(){ //default constructor
}
logic_gate(int k){ //another constructor needed
x = k;
}
};
int main(){
cout << endl << "Please enter the values of each bit below . . ." << endl;
vector<logic_gate> and_gate; //no need to tell size while declaration
string b;
while(getline(cin, b)){ //read whole line from standard input
if (b == "\0") //input is NULL
break;
and_gate.push_back(logic_gate(stoi(b))); //to convert string to integer
}
if (!and_gate.empty()){
int output = and_gate[0].x;
for (int i = 1; i < and_gate.size(); i++){
output = output & and_gate[i].x;
}
cout << "And of inputs is: " << output << endl;
}
else{
cout << "No input was given!\n";
}
return 0;
}
Feel free to ask if some doubts linger
I figured out what I wanted to do. Thanks to everyone who helped and especially Paul Sanders. Below is my final code.
#include <iostream>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput;
int output = 1;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
if (userInput == 1) {
output = userTest1;
cout << "The test of " << userTest1 << " is " << output << endl << endl;
}
else if (userInput > 1) {
for (int i = 0; i < userInput; i++) {
if (!and_gate[i].x)
{
output = 0;
break;
}
}
cout << "The test of ";
for (int i = 0; i < userInput; i++) {
cout << and_gate[i].x;
}
cout << " is " << output << endl << endl;
}
return 0;
}
I am trying to write a small program that takes a user-defined string of a limited selection of characters (lowercase letters, parentheses, and the + and * operators), looks at each of the characters, and organizes them into separate arrays. I thought my approach to this exercise would be fairly straightforward, but I have run into some issues that I cannot figure out.
My problem becomes evident when I attempt to print the individual arrays to the screen. If all of the characters are of the same type (for example, "abcd"), the arrays print as intended. But if there is a combination of character types (for example, "(a+b)"), the arrays print incorrectly. I'm ashamed to say I have been banging my head against this (probably obvious) problem for many hours now and cannot seem to figure out what I have done wrong. Any input would be appreciated - I'm not looking for help writing the program, I just want to know what I have done wrong. I have included my code below:
#include <iostream>
#include <string>
using namespace std;
void charOrganizer(int[], char[], char[], char[], int, int&, int&, int&);
int main()
{
//Variable declaration
string userExpression;
int expressionArray[userExpression.length()];
char letterToken[userExpression.length()];
char parenthesesToken[userExpression.length()];
char plusTimesToken[userExpression.length()];
int letterTokenPos = 0;
int parenthesesTokenPos = 0;
int plusTimesTokenPos = 0;
//Prompt user for string input
cout << "Please enter a mathematical expression only using lowercase letters of the \nalphabet, parentheses, and/or the addition/multiplication operators."<< endl;
cin >> userExpression;
int arraySize = userExpression.length();
for (int i = 0; i < arraySize; ++i)
{
expressionArray[i] = userExpression[i];
}
charOrganizer(expressionArray, letterToken, parenthesesToken, plusTimesToken, arraySize, letterTokenPos, parenthesesTokenPos, plusTimesTokenPos);
//Print tokens to screen
cout << "LowerCase Letter Token values in your string:" << endl;
for (int i = 0; i < letterTokenPos; i++)
{
cout << letterToken[i] << endl;
}
cout << "Parentheses Token values in your string:" << endl;
for (int i = 0; i < parenthesesTokenPos; i++)
{
cout << parenthesesToken[i] << endl;
}
cout << "Operator Token values in your string:" << endl;
for (int i = 0; i < plusTimesTokenPos; i++)
{
cout << plusTimesToken[i] << endl;
}
return 0;
}
void charOrganizer (int charValue[], char letArr[], char parArr[], char pluTimArr[], int size, int& letPosition, int&parPosition, int& operPosition)
{
for (int i = 0; i < size; i++)
{
if (charValue[i] > 96 && charValue[i] < 123)
{
letArr[letPosition] = charValue[i];
cout << "Letter Copy Test: " << letArr[letPosition] << endl;
letPosition++;
}
else if (charValue[i] == 40 || charValue[i] == 41)
{
parArr[parPosition] = charValue[i];
cout << "Parentheses Copy Test: " << parArr[parPosition] << endl;
parPosition++;
}
else if (charValue[i] == 42 || charValue[i] == 43)
{
pluTimArr[operPosition] = charValue[i];
cout << "Operator Copy Test: " << pluTimArr[operPosition] << endl;
operPosition++;
}
else
{
cout << "Invalid input" << endl;
}
}
/*cout << "Print Array Test: " << endl;
for (int i = 0; i < letPosition; i++)
{
cout << letArr[i] << endl;
//cout << parArr[i] << endl;
//cout << pluTimArr[i] << endl;
}*/
}
see your below code. You are using the length of a empty string to declare arrays size like below. In this case all the array size will zero size only. Correct it properly:-
//Variable declaration
string userExpression;
int expressionArray[userExpression.length()];// it would be just like int expressionArray[0];
char letterToken[userExpression.length()];
char parenthesesToken[userExpression.length()];
char plusTimesToken[userExpression.length()];
int expressionArray[30];
char letterToken[30];
char parenthesesToken[30];
char plusTimesToken[30];
Else you declare these variables after you enter your string.
I'm trying to store hexadecimal values into some form of an array from a file then change those numbers to binary. So far the program I wrote is only collects the last value. The file looks something like this. note(a 1 or 0 is before each hex value)
1 408ed4
0 10019d94
0 408ed8
1 10019d88
0 408edc
0 1001322
My code is #include
#include <fstream>
#include <string>
#include <cstdlib>
#include <bitset>
#include <sstream>
#define MAX_ADDRESSES 1000000
using namespace std;
int main(int argc, char **argv) {
//Declare variables
int szL1 = atoi(argv[2]);
int szL2 = atoi(argv[4]);
string type = argv[6]; //Determines the type of cache
//string fileN = argv[7];
int info, i = 1, j = 1; //info is what is read in, i & j are testing variables
string *rd_add = new string[MAX_ADDRESSES]; //set the max string length for what's read
string *wrt_add = new string[MAX_ADDRESSES]; //set the max string length for what's written
int total = 0; //total # of reads/writes
int rds = 0; //base # of reads
int wrt = 0; //base # of writes
int array_size = 1001024;
char *array = new char[array_size];
int position = 0;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof() && position < array_size){
fin.get(array[position]);
position++;
}
array[position - 1] = '\0';
for (int x = 0; array[x] != '\0'; i++){
cout << array[i];
}
}
else{
cout << "File could not be opened" << endl;
}
//check for a power of 2 for szL1
while (1)
{
if (i == szL1)
break;
//Error Message
else if (i > szL1)
{
cout << "Error. sizeL1 must be a power of 2. Please try again." << endl << endl;
return 0;
}
i *= 2;
}
//cout << "size1 " << szL1 << endl;
//check for a power of 2 for szL2
while (1)
{
if (j == szL2)
break;
//Error
else if (j > szL2)
{
cout << "Error. sizeL2 must be a power of 2. Please try again." << endl << endl;
return 0;
}
j *= 2;
}
//cout << "size2 " << szL2 << endl;
//Check to see if szL2 is larger than szL1
if (szL2 <= szL1)
{
cout << "Error. sizeL2 must be larger than sizeL1. Please try again." << endl << endl;
return 0;
}
//Read file contents*****
while (cin >> info) //check this part
{
//If it is a 1, increment read files
if (info == 1)
{
cin >> rd_add[i++];
rds++;
}
else if (info == 0)
{
cin >> wrt_add[j++];
wrt++;
}
else
{
continue;
}
}
total = rds + wrt;
//Print the arguments read
cout << endl << "Input Parameters read:" << endl;
cout << "SizeL1: " << szL1 << endl;
cout << "SizeL2: " << szL2 << endl;
cout << "Type: " << type << endl;
//Print file stats
cout << endl << "Memory References Read from File" << endl;
cout << "Total: " << total << endl;
cout << rds << " Reads" << endl;
cout << wrt << " Writes" << endl;
return 0;
}
If you want to get only the hexadecimal values in a vector and your file is as you said you can just do it as below:
String hexValue, dummy;
Vector<String> hexValueVector;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof()){
fin >> dummy >> hexValue;
hexValueVector.push_back(hexValue);
....//your remaining code
Do not forget to include the Vector library.
#include <vector>
Hope this will help you.
EDITED:
if you need the dummy too you have just to put both values in a structure:
struct myStructure{
String dummy;
String hexValue;
};
and instead of creating a vector of string you create a vector of myStructure:
Vector<myStructure> myStructureVector;
to fill your vector you have just to do this:
myStructure myStructure;
if(fin.is_open()){
...
while (!fin.eof()){
fin >> myStructure.dummy >> myStructure.hexValue;
myStructureVector.push_back(myStructure);
If this solves your problem, please vote for the answer.
About Vector, it is a STL container, if you want more details about it check http://www.cplusplus.com/reference/vector/vector/
Ok I have been struggling with this code and I think I have it written out right but here is the rules from my teacher
1 = implies right Number, Right Place.
2 = implies right Number, Wrong Place.
0 = implies Wrong Number.
So the computer decides on 12345; the user guesses 11235; the computer should respond with 10221. Hint: Watch out for a double number like 11 when there is only one.
I have it where it does all of that except I can not get it to show a 0 when it is wrong can you please help me every single part is written except that part here is my code
// Programming 2
// Mastermind
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
struct fields{//the list of variables used in my program
int size = 5;;
int range = 9;
char lowest = '0';
string guess;
string answer;
int number;
int correct;
int position;
bool gameover = false;
};
void gameplay(fields & info);//declaring the function
int main()
{
fields game;
gameplay(game);//calling the function
system("pause");
return 0;
}
void gameplay(fields & info){//calling the structure into the function
srand(time(0));//to randomize number
info.answer = "";//getting the number
for (int i = 0; i < info.size; i++)
{
char ch = info.lowest + rand() % info.range;
info.answer += ch;
}
info.number = 1;
info.correct = 0;
info.position = 0;
while (!info.gameover)//using a while loop to let them go until they guess it
{
cout << "Guess #" << info.number << ": Enter 5 numbers that are '0' through '9': ";//asking them to guess
cout << info.answer;
cout << "\n";
cin >> info.guess;
if (info.guess == info.answer)//if the guess is right this will end the game
{
cout << "Right! It took you " << info.number << " move";
if (info.number != 1) cout << "s";
cout << "." << endl;
info.gameover = true;
}
int correctNumbers = 0;
for (char const &ch : info.guess) //seeing if there are numebrs in the guess that is in the answer
{
if (info.answer.find(ch) != string::npos)
{
++correctNumbers;
}
}
int const digits = 5;
int correctPositions = 0;
int correctPosition[digits];
int test = 0;
for (int i = 0; i < digits; ++i)//telling which numbers is correct and displaying the 2 or 0 for number is correct or number is wrong
{
if (info.answer[i] == info.guess[i])
{
++correctPositions;
}
if (info.answer[i] == info.guess[i]){
correctPosition[i] = 2;
cout << correctPosition[i];
}
if (correctPosition[i] != 2){
correctPosition[i] = 1;
cout << correctPosition[i];
}
if (correctPosition[i] != 2 && correctPosition[i] != 1)){
correctPosition[i] = 0;
cout << correctPosition[i];
}
}
cout << "\nYou have " << correctPositions << " numbers in the correct position " <<endl;
cout << "You have " << correctNumbers <<" correct numbers in the wrong position"<< endl;
}
cout << "GAME OVER\n\n";
}
So I'm trying to complete this part of a program where I have to read a text file from Stdin and add it to the 'word list' wl. I get how to read from a text file but I don't know how to go about adding 'words' to a list, if that makes sense. So here's what I got:
string getWord(){
string word;
while (cin >> word){
getline(cin, word);
}
return word;
}
void fillWordList(string source[], int &sourceLength){
ifstream in.file;
sourceLength = 50;
source[sourceLength]; ///this is the part I'm having trouble on
Source is an array that determines how many words are read from the text and length is the amount printed on screen.
Any ideas on what I should begin with?
EDIT: Here's the program I'm writing the implementation for:
#include <iostream>
#include <string>
#include <vector>
#include "ngrams.h"
void help(char * cmd) {
cout << "Usage: " << cmd << " [OPTIONS] < INPUTFILE" << endl;
cout << "Options:" << endl;
cout << " --seed RANDOMSEED" << endl;
cout << " --ngram NGRAMCOUNT" << endl;
cout << " --out OUTPUTWORDCOUNT" << endl;
}
string source[250000];
vector<string> ngram;
int main(int argc, char* argv[]) {
int n, outputN, sl;
n = 3;
outputN = 100;
for (int i = 0; i < argc; i++) {
if (string(argv[i]) == "--seed") {
srand(atoi(argv[i+1]));
} else if (string(argv[i]) == "--ngram") {
n = 1 + atoi(argv[i+1]);
} else if (string(argv[i]) == "--out") {
outputN = atoi(argv[i+1]);
} else if (string(argv[i]) == "--help") {
help(argv[0]);
return 0; }
}
fillWordList(source,sl);
cout << sl << " words found." << endl;
cout << "First word: " << source[0] << endl;
cout << "Last word: " << source[sl-1] << endl;
for (int i = 0; i < n; i++) {
ngram.push_back(source[i]);
}
cout << "Initial ngram: ";
put(ngram);
cout << endl;
for (int i = 0; i < outputN; i++) {
if (i % 10 == 0) {
cout << endl;
}
//put(ngram);
//cout << endl;
cout << ngram[0] << " ";
findAndShift(ngram, source, sl);
} }
I'm supposed to use this as a reference but it dosen't help me too much.
Declaring raw array requires the size of the array to be a compile-time constant. Use std::vector or at least std::array instead. And pass source by reference if you want to fill it.