Below I have pasted some code I wrote. The problem I am having is when turnmessage passes a number to found() (by reference) it is somehow increased drematically. For example if 3 is passed in I receive 3 million.
(the following is in the file projectmain.cpp)
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "project1.h"
using namespace std;
project1 game;
string str(int number){
stringstream ss;
ss << number;
string result = ss.str();
return result;
}
void project1::setNames(){
string name;
cout<< "Player one, enter your name: ";
cin >> name;
playerOneName = name;
cout<< "Player two, enter your name: ";
cin >> name;
}
void project1::resetBoard(){
for(int i = 0; i < 3; i++){
RowOne[i] = str(i + 1);
RowTwo[i] = str(i + 4);
RowThree[i] = str(i + 7);
}
int used[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1};
turn = 1;
}
void project1::printBoard(){
for(int i = 0; i < 3; i++){
cout << " | " << RowOne[i] << " | ";
}
cout << endl;
for(int i = 0; i < 3; i++){
cout << " | " << RowTwo[i] << " | ";
}
cout << endl;
for(int i = 0; i < 3; i++){
cout << " | " << RowThree[i] << " | ";
}
cout << endl;
}
string project1::PlayerOneName(){
return playerOneName;
}
string project1::PlayerTwoName(){
return playerTwoName;
}
bool project1::found(int& number){
cout << " your number after pass: " << number;
int i = 0;
bool found = false;
while(i < 9 && found == false){
cout << used[i];
if(used[i] == number)
found = true;
i++;
}
return found;
}
void project1::turnmessage(){
int number = -1;
bool found;
do{
if(turn == 1)
cout << PlayerOneName();
else
cout <<PlayerTwoName();
cout << " it's your turn!" << endl << "Enter the number you wish to use: ";
cin >> number;
number--;
bool found = game.found(number);
if (found == true)
cout << "Sorry, that has already been used. Please try again.";
}while(found == true);
}
int main(){
game.setNames();
game.resetBoard();
game.printBoard();
game.turnmessage();
return 0;
}
(the following is in the file project1.h)
#include<string>
#include<iostream>
using namespace std;
class project1{
public:
void setNames();
void resetBoard();
void printBoard();
void turnmessage();
string PlayerOneName();
string PlayerTwoName();
bool found(int&);
private:
int playerOneScore;
int playerTwoScore;
string playerOneName;
string playerTwoName;
string RowOne[3];
string RowTwo[3];
string RowThree[3];
int used[9];
int turn;
};
I think the issue is here, in resetBoard:
int used[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1};
This creates a local variable called used that's equal to the array of -1's, rather than changing the used data member to hold all -1's. To fix this, try replacing this code with the following:
for (int i = 0; i < 9; i++) {
used[i] = -1;
}
There might be other issues there, but this is certainly suspicious.
Hope this helps!
number is not being changed to some large value in project1::found it is your output from this std::cout that is confusing you:
while(i < 9 && found == false){
cout << used[i];
if you change it to this, it will be obvious what is going on:
while(i < 9 && found == false){
cout << std::endl << used[i];
^^^^^^^^^
of you could add an std::endl here as well:
cout << " your number after pass: " << number << std::endl ;
Related
I want this c++ program to find the the words starting with user entereed letter and print them using a new function.but the thins is that it only finds 1st letter for the second time it runs ina loop and then , i dont know what happens ... I am a beginner please help me!
uncomment the line that are necessary
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getUserInput(string *filename, string *find)
{
cout << "file name : ";
cin >> *filename;
cout << "required character : ";
cin >> *find;
}
string* processFile(string fileName, string word, int *t, int *w, string found[])
{
fstream file;
int countIn = 0,
totaal = 0;
int *count = &countIn;
int *total = &totaal;
int i = 0;
string find; // the max length of the file should not exceed this value is if does please change it here.
file.open(fileName, ios::in);
if (file.is_open())
{
while (!file.eof())
{
file >> find;
totaal++;
if (word == find)
{
char a[100];
int s = find.size();
for (int j = 0; i < find.size(); j++)
{
string(1, find[i]);
}
found[i] = find;
i++;
countIn++;
}
}
}
else
cout << "!!!!invalid file name!!!!\n";
file.close();
//for (int i = 0, j = 0; i < totaal; i++)
//{
//
// cout << find[i] << '\t' << find[i][0] << endl;
//
// if (word == find[i][0])
// {
// cout << "i is " << i << endl;
// cout << "j is " << j << endl;
// cout << "Calculated i and j\n";
// found[j] = find[i];
// cout << "found[j] " << found[j] << "\nfind[i] " << find[i] << endl;
// j++;
// countIn++;
// cout << "Inside if\n";
// }
// cout << "outsidenside if\n";
//}
*t = *total;
*w = *count;
//cout << countIn << endl << totaal << endl;
//cout << *count << endl << *total<<endl;
return found;
}
void displayOutput(int total, int count, string wordlist[])
{
cout << "Total words in the file: " << total;
if (count != 0)
{
cout << "\nTotal " << count << " related words found in the file\n";
for (int i = 0; i < count; i++)
cout << i + 1 << "\t" << wordlist[i] << endl;
}
else
cout << "No matching case found\n";
}
int main()
{
string nameoffile;
string wordtofind;
string *ptr1 = &nameoffile;
string *ptr2 = &wordtofind;
string foundwords[] = { "" };
int occur = 0,
totalWords = 0;
int *occ = &occur;// occurence of the certain word
int *tot = &totalWords;// total wods in the file
getUserInput(ptr1, ptr2);
processFile(nameoffile, wordtofind, occ, tot, foundwords); //calling the processing function
displayOutput(occur, totalWords, foundwords);
return 0;
}
I am trying to add commas to a set of numbers in an array.
I have a program that will take in random numbers the length of which are determined by the user's input. These numbers are stored in a pointer array. I made another array to store the converted numbers from int to string. Now I am working on a function to add commas to them. I am having an issue with this function. infoArrayString is the converted numbers of user input from int to string. The issue is in the addCommas function
#include <iostream>
#include <string>
using namespace std;
void validNumber(int & x){
while (cin.fail()){
cout << "ERROR: must be a number, try again ->";
cin.clear();
cin.ignore(1000, '\n');
cin >> x;
}
}
void validNumberPointer(int *& x){
while (cin.fail()){
cout << "ERROR: must be a number, try again ->";
cin.clear();
cin.ignore(1000, '\n');
cin >> *x;
cout << endl;
}
}
void amount(int & userAmount, const int & MIN_INPUT, const int & MAX_INPUT)
{
/*
* Asks how many number they want
*/
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
/*
* check
*/
validNumber(userAmount);
while ((userAmount < MIN_INPUT) or (userAmount > MAX_INPUT)){
cout << "ERROR: number out of range" << endl;
cout << "Please enter numbers in range of " << MIN_INPUT << " to " << MAX_INPUT << " ->";
cin >> userAmount;
}
}
void getInfo(int *& infoArray, int & userAmount){
for(int i = 0; i < userAmount; i++){
cout << "Input number #" << i+1 << " ->";
cin >> *(infoArray+i);
cout << endl;
/*
* check
*/
validNumberPointer(infoArray);
while (*(infoArray+i) < 0){
cout << "ERROR: number out of range" << endl;
cout << "Please enter numbers in range of range -> ";
cin >> *(infoArray+i);
cout << endl;
}
}
}
void convertString(int *& infoArray, string *& infoArrayString, int & userAmount){
for(int i = 0; i < userAmount; i++){
*(infoArrayString +i) = to_string(*(infoArray+i));
}
}
void addCommas(string *& infoArrayString){
for(int i = 0; i < infoArrayString[i].length(); i++){
if(i%3 == 0 and i != 0){
infoArrayString[i] = infoArrayString[i] + ",";
}
}
}
void displayBoard(string *& infoArrayString, int & userAmount){
cout << "The sum of: " << endl;
for(int i = 0; i < userAmount; i++){
cout << *(infoArrayString++) << endl;
}
}
int main() {
const int MIN_INPUT = 2, MAX_INPUT = 11;
int userAmount = MIN_INPUT;
int * infoArray = NULL;
infoArray = new int [MAX_INPUT];
string * infoArrayString = NULL;
infoArrayString = new string [MAX_INPUT];
amount(userAmount, MIN_INPUT, MAX_INPUT);
getInfo(infoArray, userAmount);
convertString(infoArray,infoArrayString,userAmount);
addCommas(infoArrayString);
displayBoard(infoArrayString, userAmount);
}
If there is not specific reason you are using a raw array in C++ you may want to use a std::vector. They are easier to manipulate.
void int_to_string(std::vector<int>& integer_list,
std::vector<std::string>& string_list) {
// You can read integers/strings (with streams) into a
// container directly this function is for demo purposes.
for (auto& element : integer_list)
string_list.push_back(std::to_string(element));
}
You can then pass that vector of strings to a function that modifies each entry to have a comma.
void add_commas_to_strings(std::vector<std::string>& S) {
for (auto& element : S)
element += ',';
}
You may just want the commas for formatting. In that case you don't have to mutate the values of the vector.
If a csv style format is what you are after then you may be after something like this:
// Formats csv file style output.
void format_with_commas(std::vector<std::string>& string_list) {
int line_break = 0;
for (int i = 0; i < string_list.size(); ++i) {
if (line_break == 3) {
std::cout << "\n";
line_break = 0;
}
int is_end = line_break + 1;
if (is_end == 3) {
std::cout << string_list[i];
++line_break;
} else {
std::cout << string_list[i] << ", ";
++line_break;
}
}
}
Now if you really want the user to specify the length of a list perhaps try calling something like:
std::vector<int> user_defined_vector(std::vector<int>::size_type sz) {
return std::vector<int>(sz, 0);
}
The above can be ran like so:
#include <iostream>
#include <vector>
int main() {
std::vector<int> A{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<std::string> B;
int_to_string(A, B);
format_with_commas(B);
auto ten_element_vector_of_ints = user_defined_vector(10);
return 0;
}
I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10). For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':
1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
I can't get the user's input to calculate correctly when using the for loop.
Well you can try this to get that output
#include<iostream>
using namespace std;
int main()
{
int n; //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
table[i][0] = i + 1;
table[i][1] = n;
table[i][2] = table[i][0] * table[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
Output
SOLVED: Everything seems to be working now!! Here's the code:
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include <ctime>
using namespace std;
void displayTable(int table[10][3]);
bool testMe(int testTable[10][3]);
void createTables(int testTable[10][3], int ansTable[10][3], int
usersChoice);
bool AllAnswersAreTested(bool tested[10]);
void gradeMe(int testTable[10][3], int ansTable[10][3]);
void displayMenu();
int main()
{
srand(time(NULL));
int userInput = 0;
int tableChoice = 0;
int myTable[10][3] = {0};
int testTable[10][3];
int ansTable[10][3];
bool tested = false;
do
{
displayMenu(); //Display the menu of choices
cin >> userInput;
cout << endl;
switch (userInput) //Validate menu choices 1-4
{
case 1: //Display a users choice of table
displayTable(myTable);
break;
case 2: //Test user on users choice of table
cout << "What times table test would you like to take? > ";
cin >> tableChoice;
createTables(testTable, ansTable, tableChoice);
tested = testMe(testTable);
if (tested)
{
gradeMe(testTable, ansTable);
}
break;
case 3: //Display a new table of the users choice
displayTable(myTable);
break;
case 4: //Quit program menu option
cout << "Program ending.\n";
return 0;
default: //Invalid entry
cout << "You entered an invalid item number. Please enter a number from 1 to 4.\n";
cout << endl;
}
} while (userInput != 4);
return 0;
}
void displayTable(int myTable[10][3])
{
int num; //initialize local variables
//Ask the user what times table they would like to review
cout << "What times table would you like to review?" << endl;;
cout << "Please enter a value from 1 to 12 > \n";
cout << "\n";
cin >> num;
cout << endl;
for (int i = 0; i < 10; i++)
{
myTable[i][0] = i + 1;
myTable[i][1] = num;
myTable[i][2] = myTable[i][0] * myTable[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << setw(3)<< myTable[i][0] << " * " << myTable[i][1] << " = " << myTable[i][2] << endl;
}
cout << endl;
}
void createTables(int testTable[10][3], int ansTable[10][3], int usersChoice)
{
for (int i = 0; i < 10; i++)
{
testTable[i][0] = i + 1;
testTable[i][1] = usersChoice;
testTable[i][2] = 0;
ansTable[i][0] = i + 1;
ansTable[i][1] = usersChoice;
ansTable[i][2] = usersChoice * (i + 1);
}
}
bool testMe(int testTable[10][3])
{
bool tested[10] = { false, false, false, false, false,false, false, false, false, false };
while (!AllAnswersAreTested(tested))
{
int index = rand() % 10;
if (tested[index] == false)
{
int randomNum = testTable[index][0];
int tableChoice = testTable[index][1];
int answer;
cout << "What is " << randomNum << " X " << tableChoice << " = ";
cin >> answer;
testTable[index][2] = answer;
tested[index] = true;
}
}
return true;
}
bool AllAnswersAreTested(bool tested[10])
{
for (int i = 0; i < 10; i++)
{
if (tested[i] == false)
{
return false;
}
}
return true;
}
void gradeMe(int testTable[10][3], int ansTable[10][3])
{
int correctAnswers = 0;
for (int i = 0; i<10; i++)
{
if (testTable[i][2] == ansTable[i][2])
{
correctAnswers++;
}
}
int score = (correctAnswers * 10);
if (score == 100)
{
cout << "You passed the test! PERFECT SCORE!!" << endl;
cout << endl;
}
else if (score >= 70)
{
cout << "You passed the test. Your Score is: ";
cout << score;
cout << endl;
}
else if (score < 70)
{
cout << "You did not pass the test. Your Score is: ";
cout << score;
cout << endl;
}
}
//Display the menu function
void displayMenu()
{
cout << " Multiplication Tables" << endl;
cout << endl;
cout << " 1. Review MyTable" << endl;
cout << " 2. Test Me" << endl;
cout << " 3. Enter a New Multiplication Table (1-12)";
cout << " 4. Quit" << endl;
cout << " Enter a Menu Item > ";
}
#include <iostream>
using namespace std;
int main()
{
int a[100][100];
for(int i=1;i<10;i++){
for(int j=1;j<10;j++){
a[i][j] = (i)*(j);
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
There is how the output looks like:
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
I was given a assignment in college. I was asked to create a c++ console application that would read in five countries from a simple .txt file and allow a user to allocate each team a vote [6, 8, 10, 12]. Each team may vote only once, no duplicate scores and they may not vote for themselves.
We have to then display the scores in descending order to the user using a bubble sort. Practically every element of the application was working up until I had to print the scores in order.
I'm having difficulty with the calculation of the total score and also with the while loop in 'getValidCountry()'
#include <iostream>
#include <fstream> // include the 'fstream' standard library header file
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//VARIABLES
#define POINTS 4
#define NUM_COUNTRIES 5
int points[POINTS] = {6, 8, 10, 12};
vector<string> countries;
int countryInd[NUM_COUNTRIES] = {0, 1, 2, 3, 4};
int votes [NUM_COUNTRIES][NUM_COUNTRIES];
int voteTotal[NUM_COUNTRIES] = {0,0,0,0,0};
//METHOD HEADINGS
void printarray (int arg[], int length);
void voting(int votingCountry);
int getValidVote();
void printRankedTable();
void printContestants();
void BubbleSort(int arr[], int n);
void resetPoints();
int getValidCountry();
int main ()
{
ifstream inFile;
inFile.open("countries.txt"); // bind the inFile stream to a file name
if( !inFile ) // test to see if it opened successfully
{
cout << "Failed to open file." << endl;
exit( EXIT_FAILURE );
}
int i = 0;
string str;
string fileContents;
//RESERVE 5 SPACES IN THE VECTOR
countries.reserve(NUM_COUNTRIES);
vector<string>::iterator iter;
while( getline( inFile, str ) )
{
countries.push_back(str);
}
inFile.close();
printContestants();
int round = 5;
int cInd = -1;
while(round > 0)
{
cout << endl;
cInd = getValidCountry();
voting(cInd);
BubbleSort(voteTotal, NUM_COUNTRIES);
printRankedTable();
cInd = -1;
round--;
}
}
int getValidCountry()
{
bool temp = false;
string foo;
cout << "Enter Country You Wish To Vote For: ";
getline(cin, foo);
while(!temp)
{
for(int i = 0; i < NUM_COUNTRIES; i++)
{
if(foo.compare(countries.at(countryInd[i])) == 0)
{
temp = true;
return countryInd[i];
}
}
cout << "[ERROR]: Enter A Valid Country: ";
getline(cin, foo);
}
return -1;
}
void printarray (int arg[], int length) {
for (int n=0; n<length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
void voting(int votingCountry)
{
int score = 0;
for(int i = 0; i < NUM_COUNTRIES; i++)
{
if(countryInd[i] != votingCountry)
{
cout << "Please Enter Score For " << countries.at(countryInd[i]) << ": ";
score = getValidVote();
cout << score << endl;
voteTotal[countryInd[i]] = voteTotal[countryInd[i]] + score;
cout << "vote total: " << voteTotal[countryInd[i]] << "\t CountryInd: " << countryInd[i] << endl;
}
}
resetPoints();
cout << endl;
}
void resetPoints()
{
points[0] = 6;
points[1] = 8;
points[2] = 10;
points[3] = 12;
}
int getValidVote()
{
bool isValid = false;
int vote;
while(!isValid)
{
cin >> vote;
for(unsigned int i = 0; i <= POINTS; i++)
{
if (vote == points[i] && vote > -1)
{
isValid = true;
points[i] = -1;
return vote;
}
}
cout << "Enter Valid Score: ";
}
return 0;
}
void printContestants()
{
cout << endl << "EUROVISION CONTESTANTS\n";
for(unsigned int i = 0; i < NUM_COUNTRIES; i++)
{
cout << countries[countryInd[i]] << endl;
}
cout << endl;
}
void printRankedTable()
{
cout << endl << "EUROVISION CONTESTANTS [RANKED]\n";
for(unsigned int i = 0; i < NUM_COUNTRIES; i++)
{
cout << countries.at(countryInd[i]) << "\t" << voteTotal[i] << endl;
}
cout << endl;
}
void BubbleSort(int arr[], int n)
{
bool swapped = true;
int j = 0;
int tmp;
int tmpC;
while (swapped)
{
swapped = false;
j++;
for (int i = 0; i < n - j; i++)
{
if (arr[i] < arr[i + 1])
{
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
tmpC = countryInd[i];
countryInd[i] = countryInd[i+1];
countryInd[i+1] = tmpC;
swapped = true;
}
}
}
}
The problem:
When you are voting(), you enter the score to voteTotal using countryInd index:
voteTotal[countryInd[i]] = voteTotal[countryInd[i]] + score; // in voting()
So you expect that the order of the countries names and their related score id both use the access sequence defined in countryInd[].
// score of countries.at(countryInd[i]) corresponds to valueTotal[countryInd[i]]
When you BubbleSort(), you swap the elements in both countryInd[] AND in voteTotal[]. This is the cause of your problem, because the right access sequence for the country names is still countryInd[i] but it's now i for the score:
//score of countries.at(countryInd[i]) corresponds now to valueTotal[i]
You already know this, because that's exactly the logic you use in printRankedTable()
Unfortunately, when you take the second voting run, you assume again that both tables use the same access sequence defined in countryInd[] , which is an hypotheses which is no longer valid. You end up adding the voting given for one country to the total of another.
The solution
Change in BubbleSort() the if clause as follows:
if (arr[countryInd[i]] < arr[countryInd[i + 1]]) // indirect access through countryInd
{
//tmp = arr[i]; delete => no longuer needed
//arr[i] = arr[i + 1]; delete => no longuer needed
//arr[i + 1] = tmp; delete => no longuer needed
tmpC = countryInd[i];
countryInd[i] = countryInd[i + 1];
countryInd[i + 1] = tmpC;
swapped = true;
}
Also update the printRankedTable() the output instruction to:
cout << countries.at(countryInd[i]) << "\t" << voteTotal[countryInd[i]] << endl; // only indirect access via countryInd
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";
}