Comparing strings in a 2D array to user input - c++
I'm trying to get the user to choose a team (names are contained in 2D array), type the desired name/team, then use a for loop to compare the user's typed word with the words of a 2D array, and use that loop to access each string in the array:
#include <string>
#include <iostream>
#include <string.h>
int main(int argc, char* argv[]){
char cPlaychar[10][15] = { "BlackFurs", "EppiGods", "FairyDusters",
"Dwarvin", "Bloods", "Cryptics", "ArcAngels",
"DarkVillians", "Heroiteks", "Mass", };
char cKeyInput[15];
int results[10];
std::cout << "Please select a character
by typing the name and pressing enter" << std::endl;
std::cin >> cKeyInput;
for(int Array = 0; Array < 10; Array++){
switch (Array){
case '0':
results[0] = strcmp(cPlaychar[Array], cKeyInput);
if (results[0] = 0){
std::cout << "you have picked the first char";
}
break;
case '1': results[1] = strcmp(cPlaychar[Array], cKeyInput);
if (results[1] = 0){
std::cout << "you have picked the secound char";
}
break;
case '2':results[2] = strcmp(cPlaychar[Array], cKeyInput);
if (results[2] = 0){
std::cout << "you have picked the third char";
}
break;
case '3':results[3] = strcmp(cPlaychar[Array], cKeyInput);
if (results[3] = 0){
std::cout << "you have picked the fourth char";
}
break;
case '4':results[4] = strcmp(cPlaychar[Array], cKeyInput);
if (results[4] = 0){
std::cout << "you have picked the fith char";
}
break;
case '5':results[5] = strcmp(cPlaychar[Array], cKeyInput);
if (results[5] = 0){
std::cout << "you have picked the sixth char";
}
break;
case '6':results[6] = strcmp(cPlaychar[Array], cKeyInput);
if (results[6] = 0){
std::cout << "you have picked the seventh char";
}
break;
case '7':results[7] = strcmp(cPlaychar[Array], cKeyInput);
if (results[7] = 0){
std::cout << "you have picked the eighth char";
}
break;
case '8':results[8] = strcmp(cPlaychar[Array], cKeyInput);
if (results[8] = 0){
std::cout << "you have picked the ninth char";
}
break;
case '9':results[9] = strcmp(cPlaychar[Array], cKeyInput);
if (results[9] = 0){
std::cout << "you have picked the tenth char";
}
break;
} // end of switch
} // end of for
system("pause");
return 0;
}
first you can put
using namespace std ;
in the beginning and remove all (std::)
second in if (results[ ] = 0) this must be if (results[ ] == 0)
third i don't know why you use this method , you can do it easily like this
string names[] = {"a","b"} ;
string num[] = { "first", "second" } ;
string input;
cin >> input;
for (int i = 0; i < 2; ++i)
{
if (input == names[i])
cout << "you choose" << num[i] << endl;
}
but if you want 2d array you can do this
char names[2][2] = { "a", "b" };
char num[2][7] = { "first", "second" };
char input[2];
cin >> input ;
for (int i = 0; i < 2; ++i)
{
if (!strcmp(input,names[i]))
cout << "you choose " << num[i] << endl;
}
Related
Why isn't my program doing anything at all?
I'm sorry for the vague title, but I don't know what else to say. Here is my program: #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <fstream> #include <vector> using namespace std; int main (int argc, char **argv) { //string fin; string ttl, dscp, ext; string west = "w"; string east = "e"; string north = "n"; string south = "s"; int numRooms; //string argv[1] = filename; class Room { public:string title; string description; string exits; int exitWest = -1; int exitNorth = -1; int exitEast = -1; int exitSouth = -1; int numExits; }; ifstream fin; fin.open (argv[1]); //cin.ignore(); int t = 0; while (fin) { string tilde; string tester; tester = "~"; cin >> tilde; if (tilde == tester) { t = t + 1; } (numRooms = t / 3); } Room *roomArrayPtr = new Room[numRooms]; fin.clear (); while (fin) { for (int l = 0; l < numRooms; l++) { getline (fin, ttl, '~'); roomArrayPtr[l].title = ttl; getline (fin, dscp, '~'); roomArrayPtr[l].description = dscp; getline (fin, ext, '~'); stringstream sin; sin << ext; string x; int y; while (sin >> x >> y) { if (x == west) { roomArrayPtr[l].exitWest = y; } if (x == south) { roomArrayPtr[l].exitSouth = y; } if (x == north) { roomArrayPtr[l].exitNorth = y; } if (x == east) { roomArrayPtr[l].exitEast = y; } } sin.clear (); int numext; numext = (ext.size ()) / 3; roomArrayPtr[l].numExits = numext; }} //(read in file again populate roomarrayptr w while loop and getline) //roomArrayPtr[index].title = line; //roomArrayPtr[index].description=line; //close files, while loop that reads in user input from stdin, delete pointers w (delete[] roomArrayPtr;) //if (exitsarray[i].size() > 2){ char command; char newcommand; cout << ">"; cin >> command; int currentroom = 0; int newroom; bool keepgoing = true; //string dir1; while (keepgoing) switch (command) { // stringstream ss; case 'l': cout << roomArrayPtr[currentroom].title << endl; cout << roomArrayPtr[currentroom].description << endl; cout << endl; //if (roomArrayPtr[currentroom].numExits < 2) { cout << "Exits: "; if (roomArrayPtr[currentroom].exitWest > -1) { cout << "w"; } if (roomArrayPtr[currentroom].exitNorth > -1) { cout << "n"; } if (roomArrayPtr[currentroom].exitSouth > -1) { cout << "s"; } if (roomArrayPtr[currentroom].exitEast > -1) { cout << "e"; } /*else { cout << "Exits: " ; for (int k = 0; k < numExits; k++){ cout << exitdirection << " "; } }*/ //string newcommand; cin >> newcommand; //int newroom; switch (newcommand) { case 'w': if (roomArrayPtr[currentroom].exitWest == -1) { cout << "You can't go WEST!" << endl; } else { newroom = roomArrayPtr[currentroom].exitWest; cout << "You moved WEST." << endl; } break; case 'e': if (roomArrayPtr[currentroom].exitEast == -1) { cout << "You can't go EAST!" << endl; } else { newroom = roomArrayPtr[currentroom].exitEast; cout << "You moved EAST." << endl; } break; case 'n': if (roomArrayPtr[currentroom].exitNorth == -1) { cout << "You can't go NORTH!" << endl; } else { newroom = roomArrayPtr[currentroom].exitNorth; cout << "You moved NORTH." << endl; } break; case 's': if (roomArrayPtr[currentroom].exitSouth == -1) { cout << "You can't go SOUTH!" << endl; } else { newroom = roomArrayPtr[currentroom].exitSouth; cout << "You moved SOUTH." << endl; } break; } break; case 'q': keepgoing = false; return 0; break; currentroom = newroom; } } Whenever I run it, it compiles, but nothing happens. I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up. What's going on? I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up.
you are reading the wrong file int t = 0; while (fin) { string tilde; string tester; tester = "~"; cin >> tilde; <<<<===== i assume you mean fin if (tilde == tester) { t = t + 1; } (numRooms = t / 3); }
How to read txt files into an array that are stored into class variables? [duplicate]
This question already has answers here: Reading file into array of struct c++ (3 answers) C++ Reading text file with delimiter into struct array (2 answers) C++ Reading data from text file into array of structures (2 answers) How do I read data from a text file into an array of struct (1 answer) Reading data from a text file into an array of structs (1 answer) Closed 2 years ago. #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; class BasketballPlayer { public: void printBasketballPlayer() const; BasketballPlayer(); //Constructor with Parameters private: string name; float MinutesPlayed; float PlayerScoreEffRating; float Steals; float AST; float PointPerGame; float Rebounds; float FieldGoal; float FreeThrow; float ThreePointers; float BLK; float TurnOver; }; class BasketballTeam { public: string name; void printBasketballTeam() const; bool findPlayer(string &); void editPlayer(bool&); BasketballTeam(); //Default Constructor void getName() { getline(cin, name); } private: //void BasketballPlayer(); string name; float MinutesPlayed; float PlayerScoreEffRating; float Steals; float AST; float PointPerGame; float Rebounds; float FieldGoal; float FreeThrow; float ThreePointers; float BLK; float TurnOver; string myArray[16][11]; string PlayerName[15]; float myArray[15][11]; void Team() { ifstream file("TextFileTeam.txt"); if (file.is_open()) { string myArray[16]; for (int i = 0; i < 16; ++i) { file >> myArray[i]; } } } }; int main() { BasketballPlayer Play; string Search; bool isPlayerThere; char Change; BasketballTeam Team; cout << " Welcome to the Brooklyn Net's Stats and DataBase " << endl; cout << " These are the stats of our new SuperStar " << endl; Play.printBasketballPlayer(); cout << " < Would you Like to Update stats of the roster > --> Y or --> N " << endl; cin >> Change; cout << endl; if (Change == 'Y' || 'y') { Team.findPlayer(Search); Team.editPlayer(isPlayerThere); } else { Team.printBasketballTeam(); } Team.printBasketballTeam(); return 0; }//end main void BasketballPlayer::printBasketballPlayer() const { cout << "|| The players name || " << this->name; cout << endl; cout << "|| Minutes Per Game || " << this->MinutesPlayed; cout << endl; cout << "|| Turnovers Per Game || " << this->TurnOver; cout << endl; cout << "|| Points Per Game || " << this->PointPerGame; cout << endl; cout << "|| Rebounds Per Game || " << this->Rebounds; cout << endl; cout << "|| Asists Per Game || " << this->AST; cout << endl; cout << "|| Blocks Per Game || " << this->BLK; cout << endl; cout << "|| 3 Point % || " << this->ThreePointers; cout << endl; cout << "|| Free-Throw % || " << this->FreeThrow; cout << endl; cout << "|| Field Goal %|| " << this->FieldGoal; cout << endl; cout << "|| Steals % || " << this->Steals; cout << endl; cout << "|| Player Scoreing Effiencey Rating || " << this->PlayerScoreEffRating; cout << endl; } BasketballPlayer::BasketballPlayer() //Constructor with Parameters { name = "James Harden"; MinutesPlayed = 40.2f; TurnOver = 4.2f; PointPerGame = 24.1f; Rebounds = 8.1f; AST = 12.0f; BLK = 0.6f; ThreePointers = 37.9f; FreeThrow = 89.2f; FieldGoal = 48.2f; Steals = 1.1f; PlayerScoreEffRating = 1.561f; } void BasketballTeam::printBasketballTeam() const { ifstream file("TextFileTeam.txt"); if (file.is_open()) { string myArray[16]; for (int i = 0; i < 16; ++i) { file >> myArray[i]; cout << myArray[i]; cout << endl; } } } bool BasketballTeam::findPlayer(string&) { bool Finder = false; const char *name; switch (*name) { case 1: if(name == "Kevin_Durant") Finder = true; break; case 2: if (name == "Kyrie_Irving") Finder = true; break; case 3: if (name == "James_Harden") Finder = true; break; case 4: if (name == "Joe_Harris") Finder = true; break; case 5: if (name == "Jarrett_Allen") Finder = true; break; case 6: if (name == "Jeff_Green") Finder = true; break; case 7: if (name == "Taurean_Prince") Finder = true; break; case 8: if (name == "Timothe_Luwawu - Cabarrot") Finder = true; break; case 9: if (name == "Spencer_Dinwiddie") Finder = true; break; case 10: if (name == "DeAndre_Jordan") Finder = true; break; case 11: if (name == "Bruce_Brown_Jr.") Finder = true; break; case 12: if (name == "Landry_Shamet") Finder = true; break; case 13: if (name == "Chris_Chiozza") Finder = true; break; case 14: if (name == "Reggie_Perry") Finder = true; break; case 15: if (name == "Tyler_Johnson") Finder = true; break; default: cout << " Player not in Roster " << endl; break; } return Finder; } void BasketballTeam::editPlayer(bool &) { int editValue; BasketballTeam Team; bool isThere; ifstream file("JustData.txt"); if (file.is_open()) { string myArray[15]; for (int i = 0; i < 15; ++i) { file >> myArray[i]; } } if (isThere == true) { cout << " What would you like to edit? " << endl; cout << "[1] Mintues, [2] Turnover, [3] Points Per Game, [4] Rebounds Per Game, [5] Steals Per Game, [6] Free Throw %, [7] Assits Per Game, [8] Filed Goal %" << endl; cout << "[7] Assits Per Game, [8] Filed Goal %[9] 3P%, [10] Player Scoring Eff, [11] Blocks Per Game ---> "; cin >> editValue; switch (editValue) { case 1: MinutesPlayed = editValue; break; case 2: PlayerScoreEffRating = editValue; break; case 3: PointPerGame = editValue; break; case 4: Rebounds = editValue; break; case 5: Steals = editValue; break; case 6: FreeThrow = editValue; break; case 7: AST = editValue; break; case 8: FieldGoal = editValue; break; case 9: ThreePointers = editValue; break; case 10: PlayerScoreEffRating = editValue; break; case 11: BLK = editValue; break; default: break; } } } BasketballTeam::BasketballTeam() //Default Constructor { int j; int row; int col; j = 0; ifstream file("JustData.txt"); if (file.is_open()) { float PlayerArray[15][11]; for (int row = 0; row < 15; row++) { for (int col = 0; col < 11; col++) { file >> PlayerArray[row][col]; MinutesPlayed = PlayerArray[j][col]; TurnOver = PlayerArray[j][col]; Rebounds = PlayerArray[j][col]; PointPerGame = PlayerArray[j][col]; AST = PlayerArray[j][col]; BLK = PlayerArray[j][col]; ThreePointers = PlayerArray[j][col]; FreeThrow = PlayerArray[j][col]; FieldGoal = PlayerArray[j][col]; Steals = PlayerArray[j][col]; PlayerScoreEffRating = PlayerArray[j][col]; j++; } } } ifstream file2("JustNames.txt"); if (file2.is_open()) { string PlayerName[15]; for (int row = 0; row < 15; row++) { file >> PlayerName[row]; name = PlayerName[row]; } } }; JustData.txt 36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 JustNames.txt Kevin_Durant Kyrie_Irving James_Harden Joe_Harris Jarrett_Allen Jeff_Green Taurean_Prince Timothe_Luwawu-Cabarrot Spencer_Dinwiddie DeAndre_Jordan Bruce_Brown_Jr. Landry_Shamet Chris_Chiozza Reggie_Perry Tyler_Johnson TeamNoTitle.txt Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 Bruce_Brown_Jr.,17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 TeamFileNets.txt Player,MPG,TOV,RPG,APG,SPG,BPG,PPG,FG%,3P%,FT%,SC-EFF Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 "Bruce_Brown_Jr.",17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 I'm sure that I'm not understanding Classes. Trying to use fstream to hold data of players so that my classes and driver code can change those files then display data from stored data in classes. I have no syntax errors but code not running. Most likey because of me reading file into array wrong to get data into my classes from file and improper calling of classes in main function.
How to display structures Arrays in functions
This program is essentially supposed to count the results of random throws of a dice 100 times and count the occurrence of each face then display all of them as a histogram of asterisks. It would seem the functions could be working but i'm unable to verify because after I make my choice, nothing displays. #include <iostream> #include <iomanip> #include <string> #include <random> #include <sstream> using namespace std; enum class Side { ONE, TWO, THREE, FOUR, FIVE, SIX }; struct Bar { int value; Side label; }; //roll dice function void rollDice( Bar h[], int n = 100); void rollDice( Bar h[], int){ default_random_engine en; uniform_int_distribution<> dist{1,6}; int results[] ={0,0}; for( int n; n<=100; n++){ cout << dist(en); results[dist(en)]++; h[n].value = results[n]; if(h[n].value == 1){ h[n].label = Side::ONE; } else if(h[n].value == 2){ h[n].label = Side::TWO; } else if(h[n].value == 3){ h[n].label = Side::THREE; } else if(h[n].value == 4){ h[n].label = Side::FOUR; } else if(h[n].value == 5){ h[n].label = Side::FIVE; } else { h[n].label = Side::SIX; } } }; string getHistogram(Bar h[], char c = '*'); string getHistogram(Bar h[], char c ){ stringstream ast; for( int n; n<=100; n++){ switch (h[n].label) { case Side::ONE: return to_string(c); break; case Side::TWO: return to_string(c); break; case Side::THREE: return to_string(c); break; case Side::FOUR: return to_string(c); break; case Side::FIVE: return to_string(c); break; case Side::SIX: return to_string(c); break; default: break; } } ast << "One: " << c << endl; ast << "Two: " << c << endl; ast << "Three: " << c << endl; ast << "Four: " << c << endl; ast << "Five: " << c << endl; ast << "Six: " << c << endl; string output = ast.str(); cout<< output; return output; } int main (){ Bar histogram[] = { {0,Side::ONE},{0,Side::TWO}, {0,Side::THREE}, {0,Side::FOUR},{0,Side::FIVE}, {0,Side::SIX} }; char choice; do { cout << "DICE ROLLING SIMULATION" << endl <<"===============================" << endl << "r. Roll Dice" << endl << "h. Display histogram" << endl << "q. Quit program\n" << endl << "\nEnter your choice:" << endl; // Reading a single character using the scanner cin >> choice; switch(choice) { case 'r': case 'R': rollDice(histogram, 100); break; case 'h': case 'H': cout<< getHistogram(histogram, '*'); break; case 'q': case 'Q': cout << "Good bye\n" << endl; break; default: cout << "Invalid choice\n" << endl; } } while(choice != 'q'); }
So, this code contains many different mistakes. Let's go in order. In structBar label may be const struct Bar { int value; const Side label; }; You don't need forward declaration for function signature In rollDice you have many unnecessary local variables and I would use mt19937 random generator. So rollDice will look like this void rollDice(Bar h[], int count = 100) { default_random_engine en; uniform_int_distribution<> dist{1,6}; for( int n = 0; n <= count; n++) { cout << dist(en) << endl; const auto index = dist(en) - 1; ++h[index].value; } }; In getHistogram you have return to_string(c); in switch therefore you don't see histogram. You can delete swith because you can match index and Side. And why cycle up to 100? string getHistogram(Bar h[], char c = '*') { stringstream ast; for( int n = 0; n <= 5; n++) { const string strValue = string(h[n].value, c); switch (h[n].label) { case Side::ONE: ast << "One: "; break; case Side::TWO: ast << "Two: "; break; case Side::THREE: ast << "Three: "; break; case Side::FOUR: ast << "Four: "; break; case Side::FIVE: ast << "Five: "; break; case Side::SIX: ast << "Six: "; break; } ast << strValue << '(' << h[n].value << ')' << endl; } return ast.str(); } In main function you have to clear histogram before next rollDice case 'r': case 'R': for (Bar& b : histogram) { b.value = 0; } rollDice(histogram, 100); break; Full version #include <iostream> #include <iomanip> #include <string> #include <random> #include <sstream> using namespace std; enum class Side { ONE, TWO, THREE, FOUR, FIVE, SIX }; struct Bar { int value; Side label; }; void rollDice(Bar h[], int count = 100) { default_random_engine en; uniform_int_distribution<> dist{1,6}; for( int n = 0; n <= count; n++) { cout << dist(en) << endl; const auto index = dist(en) - 1; ++h[index].value; } }; string getHistogram(Bar h[], char c = '*') { stringstream ast; for( int n = 0; n <= 5; n++) { const string strValue = string(h[n].value, c); switch (h[n].label) { case Side::ONE: ast << "One: "; break; case Side::TWO: ast << "Two: "; break; case Side::THREE: ast << "Three: "; break; case Side::FOUR: ast << "Four: "; break; case Side::FIVE: ast << "Five: "; break; case Side::SIX: ast << "Six: "; break; } ast << strValue << '(' << h[n].value << ')' << endl; } return ast.str(); } int main (){ Bar histogram[] = { {0, Side::ONE}, {0, Side::TWO}, {0, Side::THREE}, {0, Side::FOUR}, {0, Side::FIVE}, {0, Side::SIX} }; char choice; do { cout << "DICE ROLLING SIMULATION" << endl <<"===============================" << endl << "r. Roll Dice" << endl << "h. Display histogram" << endl << "q. Quit program\n" << endl << "\nEnter your choice:" << endl; // Reading a single character using the scanner cin >> choice; switch(choice) { case 'r': case 'R': for (Bar& b : histogram) { b.value = 0; } rollDice(histogram, 100); break; case 'h': case 'H': cout << getHistogram(histogram, '*') << endl; break; case 'q': case 'Q': cout << "Good bye\n" << endl; break; default: cout << "Invalid choice\n" << endl; } } while(choice != 'q'); }
Pig latin conversion using Cstrings
The program takes in a word given by the user and translates that to pig latin. I've gotten everything to work almost perfectly, but have run into two bugs. The first of which is when translating words that begin with consonants say "count", the output is "ounttcay" instead of "ountcay". The second bug is that when for three letter words like "egg" or "not" the output is "egg_\377ay" or "ottn\377ay". Is there a simple way to remove that duplicate character and get rid of those numbers? Note - Unfortunately it has to be done using a Cstring #include <iostream> #include <stdio.h> #include <cstring> using namespace std; int convertToPigLatin(char arr[50]); bool isVowel(char ch); int main() { char userInput[50]; char answer = ' '; do { cout << "Enter a word to convert it to pig latin" << endl; cin.getline(userInput, 50); //get user input cout << "Your entered word is " << userInput << endl; convertToPigLatin(userInput); //translate user's input into piglatin cout << "Would you like to convert another word?" << endl; cin >> answer; cin.ignore(); //clear past user input cin.clear(); } while (answer == 'Y' || answer == 'y'); return 0; } bool isVowel (char ch) { switch (tolower(ch)) { //if the first character of the given input is a vowel case 'a': case 'e': case 'i': case 'o': case 'u': return true; default: return false; } } int convertToPigLatin(char arr[50]) { char newArr[50]; // string conjunctions[6] = {"and","but","for","nor","yet","the"}; //list of conjunctions not to be converted size_t arrLength = strlen(arr); //holds length of input for (int i = 0; i < arrLength; i++) { //make sure all characters in input are lower case for easier processing newArr[i] = tolower(arr[i]); } char lastChar = newArr[0]; //save the first character in case it needs to be appended if (atoi(arr) || arr[0] == '\0') { //if the input contains a number or begins with a null character print an error cout << "Cannot translate inputs that contain numbers" << endl; return -1; } else if (arrLength <= 2) { // if the input is 2 or less characters cout << newArr << endl; //print the input as is cout << "Boring! Try somthing more than 2 characters long" << endl; return 0; } else if ((strstr(newArr, "and") && arrLength == 3) || (arrLength == 3 && strstr(newArr, "but")) || (arrLength == 3 && strstr(newArr, "for")) || (arrLength == 3 && strstr(newArr, "nor")) || (arrLength == 3 && strstr(newArr, "yet")) || (arrLength == 3 && strstr(newArr, "the"))) { //if the input is more than 2 characters long cout << newArr << endl; //print the input as is cout << "No conjucntions try again!" << endl; return 0; } else { //if the given input is three characters and is not a conjunction, being translation if (isVowel(arr[0])) { //check if input's first character is a vowel cout << "Your word in piglatin is "<< strcat(newArr, "ay") << endl; //print that string with 'ay' at the end (i.e. egg'ay') return 0; } else { //else if the given input starts with a consonant for (int r = 1; r < arrLength; r++) { newArr[r-1] = newArr[r]; newArr[arrLength] = lastChar; } cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl; return 0; } } return 0; }
You're not terminating newArr, and the last index of the input string is arrLength - 1. int convertToPigLatin(char arr[50]) { // Make sure newArr is properly terminated. char newArr[50] = {0}; // [...] } else { //else if the given input starts with a consonant for (int r = 1; r < arrLength; r++) { newArr[r-1] = newArr[r]; } // Do this outside the loop. newArr[arrLength-1] = lastChar; // No need for strcat here. cout << "Your word in piglatin is " << newArr << "ay" << endl; } } return 0; }
You need to add the '\0' at the end of newArr because strlen does not count it so you are not copying it. strcat replaces '\0' witn 'ay\0' but you have no '\0'. for (int r = 1; r < arrLength; r++) { newArr[r-1] = newArr[r]; newArr[arrLength] = lastChar; } newArr[arrLength+1] = '\0'; cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;
problems with conditional statement based off sizeof c++
I am new to c++ and and am working on a program that has is a simple dvd rental program. I am having issues with case 3 & 4 specifically. Maybe I am misunderstanding the purpose behind sizeof. What I am trying to have it do is tell if the char array is empty and if it is allow the user to check it out by putting their name in and if it is not available give them a response saying that it is not available. case 4 should do the opposite and allow them to check it in. Any suggestions would be greatly appreciated. #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <limits> using namespace std; const int arrSize = 5; struct dvdStruct //distance struct { int id; char title[51] = { 0 }; char rating[5] = { 0 }; double price; char borrower[51] = { 0 }; } dvd; dvdStruct dvds[arrSize] = {}; int userSelection; //intput variable for main menu selection int borrowId (0); int borrowIdReturn(0); //void initalize(); int main() { int size(0); dvds[0].id = 1; dvds[1].id = 2; dvds[2].id = 3; dvds[3].id = 4; dvds[4].id = 5; strcpy(dvds[0].title, "Fast 1"); strcpy(dvds[1].title, "Fast 2"); strcpy(dvds[2].title, "Fast 3"); strcpy(dvds[3].title, "Fast 4"); strcpy(dvds[4].title, "Fast 5"); strcpy(dvds[0].rating, "PG - 13"); strcpy(dvds[1].rating, "PG - 13"); strcpy(dvds[2].rating, "PG - 13"); strcpy(dvds[3].rating, "PG - 13"); strcpy(dvds[4].rating, "PG - 13"); dvds[0].price = '19.1'; dvds[1].price = '19.2'; dvds[2].price = '19.3'; dvds[3].price = '19.4'; dvds[4].price = '19.5'; strcpy(dvds[0].borrower, ""); cout << strlen(dvds[0].borrower) << endl; strcpy(dvds[1].borrower, "\0"); strcpy(dvds[2].borrower, "\0"); strcpy(dvds[3].borrower, "\0"); strcpy(dvds[4].borrower, "\0"); do { cout << "1.Display All DVD’s" << endl << "2.Display DVD Detail" << endl << "3.Check Out a DVD" << endl << "4.Check In a DVD" << endl << "5.Exit" << endl; cin >> userSelection; //Input from the user. switch (userSelection) { case 1: for (int i = 0; i < arrSize; i++) { std::cout << dvds[i].title << "' " << dvds[i].rating << " " << dvds[i].borrower << endl; } system("pause"); system("CLS"); break; case 2: int dvdNum; cout << "Enter a DVD number:"; cin >> dvdNum; std::cout << dvds[dvdNum - 1].title << "' " << dvds[dvdNum - 1].rating << endl; system("pause"); system("CLS"); break; case 3: cout << "Enter and id:"; cin >> borrowId; if (strlen(dvds[borrowId-1].borrower) == 0) { cout << "Enter your name: "; cin >> dvds[borrowId-1].borrower; } else { cout << "This dvd is not available" << endl; } system("pause"); system("CLS"); break; case 4: cout << "Enter and id:"; cin >> borrowIdReturn; if (strlen(dvds[borrowIdReturn - 1].borrower) == 0) { cout << "This dvd is available" << endl; } else { cout << "Your DVD has been returned " << endl; strcpy(dvds[borrowIdReturn - 1].borrower, "\0"); } system("pause"); system("CLS"); break; case 5: return 0; break; } } while (userSelection == 1 || userSelection == 2 || userSelection == 3 || userSelection == 4); }
sizeof() gives you the size of an object. The size of the object is always the same, no matter what's in the object. In fact, sizeof() is calculated at compile time, and its value could not be affected, in any way, by whatever happens at runtime. C++ code should use std::string, instead of char arrays, in most cases. std::string's empty() method indicates whether the string is empty. If you still insist on working with C-style char arrays, and C-style '\0' terminated strings, use the C strlen() function to check if the character array contains nothing but a leading '\0', indicating an empty string.