Simple search program using arrays help me - arrays

When the user types in a word the program is searching for a match in an array, if there is a match the program prints out the string from the array.The code below does just that. My goal is to make it so when a word matches with a a word in the array the program should print an info not only the word. I thought I can fill the array with functions, but its not working. Is it even possible ?
I am using league of legend hero names because they are a lot and I know them and it doesent take me a lot of time to think of names that way :D
The idea is if the user types in voly, the program finds voly in the array and prints out(for example) his starting life, armor, mr and so on.
I tryed a lot of thing with functions but I cant make it work.
#include <iostream>
#include <string>
using namespace std;
string voly(string holder,string heroName);
int main(){
const int numH = 10;
string holder;
string heroName;
string heroList[numH] = {"voly", "teemo", "vladimir", "morgana", "jax", "ekko", "anivia", "nunu", "ashe", "tresh" };
cout << "Enter hero name.\n" << endl;
cin >> heroName;
for (int i = 0; i < numH; i++){
holder = heroList[i];
if (heroName == holder){
cout << holder << endl;
}
}
system("PAUSE");
return 0;
}
string voly(string holder, string heroName) {
cout << "Voly is the best" << endl;
}

Try to learn about structs. You can utilize them to encapsulate all hero information in a hero struct, as follows. This serves as kind of a prototype for each hero:
struct hero {
string name;
int hp;
int mana;
float mreg;
...
void printMe() { cout << 'hp: ' << hp << endl << 'mana: ' << mana << endl << ...; }
}
Using the printMe() function of that specific hero object, you can print its values.
Then, for each hero, create a struct object and add them to the array.
hero* pointer = new hero[numH];
pointer[0] = new hero {
name: "voly",
hp: 150
};
pointer[1] = new hero {
...
};
(Try considering some import function via a .CSV file or so.)
By using your for loop, compare the name:
for (int i = 0; i < numH; i++){
if (heroName == pointer[i].name){
pointer[i]->printMe();
}
}
Try using Google to find tutorials on that. Unfortunately, I'm not quite sure about the syntax in C++, maybe someone can help me out.
Good Luck!

Related

Utilizing the <filesystem> library; visualStudios

I'll cut the the short of it. I'm attempting to understand the filesystem library but there's very little information I've been able to find. I managed to get it to compile and understand the filesystem::path type variable really well but don't seem to understand how to get filesystem::directory_iterator to work properly. I'm not sure if I'm using it for a purpose it wasn't design for. So here is what I'm attempting to do:
I wanted to create a program that opens every text file within a specified folder. For this I need to obtain the folder name and path but I want the program to be able to obtain this information on itself and dynamically so if I add or remove textFiles it'll have the logic to function.
I'm able to create a directory_iterator variable that it manages to hold the first file with me just giving it the directory like this:
const char address[]{ "C:\\Users\\c-jr8\\ProgramBranch\\PersonalPlatform\\log extruder\\logs" };
fs::directory_iterator myIterator(address);
When testing the code in the folder I have four textFiles called "attempt 1" to "attempt 4". When reading the information on:
https://learn.microsoft.com/en-us/cpp/standard-library/directory-iterator-class?view=vs-2019#op_star
It mentions two functions to move the path object within the iterator to the next file. The first is increment(), which is the intendent method for iterating through the files, and operation++().
Now increment() hasn't been able to work for me cause it takes in a erro_code type variable and I haven't been able to find much information about how to implement this with the filesystem_errorcode variable or however it's meant to be used. The operation++() works beautifully and provides me with the path to every file but I was having issues with managing the code to detect when the operate++() functions leads to no other files. Once it iterates through every file it sorts of crashes when it keeps moving to the next. Here's that piece of code:
string tempString;
for (int i = 0; i < 5; i++) { //Here the limiting is 5 so it'll iterate onces more than the numbers of files unpurpose to see how it responses.
tempString = myIterator.operator*().path().generic_string();
ifstream tempFile(tempString);
if (!tempFile.is_open()) {
cout << "Looking at file: " << i + 1 << "; failed to open." << endl << endl;
cin.get();
return 0;
}
{
//do things with file...
}
tempFile.close();
myIterator.operator++();
}
What I want if to find a way to stop the for loop once it the iterator goes off the final file.
whichever information about how the filesystem library works it would be very much appreciated.
std::directory_iterator is a classic iterator that allows for iterating over ranges, and those are usually designated by a pair of iterators, one indicating the beginning of a sequence and another representing the past-the-end iterator.
Some iterator types, like those providing access to streams, don't have an actual end location in memory. A similar situation applies to a directory iterator. In such a case, the idiomatic approach is to use a default-constructed iterator object that will serve as an end indicator.
Having said that, you could rewrite your loop to:
for (fs::directory_iterator myIterator(address), end{}; myIterator != end; ++myIterator) {
Alternatively, you can utilize a range-based for loop:
for (auto& p : fs::directory_iterator(address)) {
tempString = p.path().generic_string();
// ...
Also, note that iterators' interface is supposed to look/behave like a pointer, hence it uses operator overloading to allow for concise syntax. So instead of:
myIterator.operator++();
you should be using:
++myIterator;
Similarly, instead of:
myIterator.operator*().path().generic_string();
juse use:
(*myIterator).path().generic_string();
or:
myIterator->path().generic_string();
You should compare myIterator with a default constructed directory_iterator to check if the last file has been processed. You can also use a much simpler form to access the operators (shown in the code below):
string tempString;
// loop until myIterator == fs::directory_iterator{}
for(size_t i = 1; myIterator != fs::directory_iterator{}; ++i) {
// access path() through the iterators operator->
tempString = myIterator->path().generic_string();
ifstream tempFile(tempString);
if(!tempFile.is_open()) {
cout << "Looking at file: " << i << "; failed to open." << endl << endl;
cin.get();
return 0;
}
{
std::cout << tempString << " opened\n";
}
// tempFile.close(); // closes automatically when it goes out of scope
// simpler form to use myIterator.operator++():
++myIterator;
}
An even simpler approach would be to use a range-based for-loop:
for(const fs::directory_entry& dirent : fs::directory_iterator(address)) {
const fs::path& path = dirent.path();
ifstream tempFile(path);
if(!tempFile) {
cout << "Looking at file: " << path << "; failed to open.\n\n";
cin.get();
return 0;
}
std::cout << path << " opened\n";
}

Codeblocks why is my code unable to open my .csv file

This is part of my code, of course I have #include fstream>, and to basically run you throught what the code should do at this point is open a file I have name "flights.csv" and in a function called readFlights count how many flights are in the file and then return the size, but when ran it returns a size of 0 when there are 5 in the file, and gives me my error file open message.
int main()
{
ifstream in("flights.csv");
if(!in.is_open()) cout << "ERROR: File open" << endl;
Flights flightsList[100];
const int SIZE = readFlights(in, flightsList);
cout << "Size: " << SIZE <<endl;
here is the function for counting the size and putting it into an array.
int readFlights(ifstream& in, Flights flightsList[100]){
//Reads the file flights.csv and returns a size used for array.
string pdStore, dmStore;
int size= 0;
while(in.good()){
getline(in, flightsList[size].fromCity,',');
getline(in, flightsList[size].toCity,',');
getline(in, pdStore,',');
flightsList[size].priceDollars = stoi(pdStore);
getline(in, dmStore,'\n');
flightsList[size].distanceMiles = stoi(dmStore);
size++;
}
return size;
}
I thought it was interesting but I don't know if this is necessary but inside code blocks the .csv part of the file in ifstream in("flights.csv"); was underlined with the red jagged lines.
I found the answer, I had no clue I had to include the file into the project folder itself...

Is it possible to get a section of a word in an array (C++11)

Let's say we a string array of full names that contains {"John Doe", "Bill Gates", "Tyler Maxwell Gordon"}
What if I wanted to get the first, middle and last names of these people?
So,
first names will be John, Bill, and Tyler
middle names will be blank, blank and Maxwell
last names will be Doe, Gates, and Gordon
Is this possible? I am a python user and very new to c++11! In python, I would figure out a way to slice. But, I noticed it is not as simple to slice in c++. So, I came to the masters for help!
Any help would be appreciated!
Thank you in advance
Sure you can. One of the easier ways to split the string up into its parts is to use std::getline with a delimiter, in your case a space character. Here is a quick example of what you're looking for.
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
std::vector<std::string> names = {"John Doe", "Bill Gates", "Tyler Maxwell Gordon"};
for (const auto& elem : names)
{
// split parts of names delimited by space
std::istringstream iss(elem);
std::string token;
std::vector<std::string> firstMiddleLast;
while (std::getline(iss, token, ' '))
{
firstMiddleLast.push_back(token);
}
// do whatever you'd like with tokenized parts...
if (firstMiddleLast.size() == 2) // -- no middle name -- //
{
std::cout << "first: " << firstMiddleLast[0]
<< "\nlast: " << firstMiddleLast[1] << std::endl;
}
else if (firstMiddleLast.size() > 2) // -- has middle name -- //
{
std::cout << "first: " << firstMiddleLast[0]
<< "\nmiddle: " << firstMiddleLast[1]
<< "\nlast: " << firstMiddleLast[2] << std::endl;
}
}
return 0;
}

How to call on a renamed file in another function? (Visual C++)

So, I'm trying to create a text file that can be written to and used to seed a random number generator, but I need to be able to write to and call on the file in all of my functions. The file has to be named with the user's first and last name so I found some code that would create a text file and rename it, I'm just having trouble calling the file in my other functions. I included the beginning part of one of my other functions after the code for the text file creation. I'm going to need to send a time stamp to the file and use that time to seed my RNG.
int user_file_name()
{
string tstamp = get_timestamp();
//Creating input/output file using user's name
ofstream user_file;
string filename;
cout << "What is your first and last name?\n" << endl;
getline(cin, filename);
filename += ".txt";
cout << "Thank you, " << filename << "." << endl << endl;
user_file.open(filename.c_str());
user_file << tstamp;
user_file.close();
return 0;
}
int addition()
{
char DIFFICULTY;
difficulty_menu();
cin >> DIFFICULTY;
get_timestamp();
string tstamp = get_timestamp();
Why not just have user_file_name return the string filename instead of just an int? You can then store that filename somewhere so that other areas of your program can access it.

Array displays correctly inside a loop, but once outside the array seems to lose all information

Im a noob at this and was wondering why my array will output correctly within the while loop but once i cout the array outside of the while loop no information is displayed?
if you can explain it in beginner terms id really appreciate it.
void Video::Read_Video()
{
ifstream Din;
Din.open("Video.txt");
if(!Din)
cerr << "Could not open video.txt for reading." << endl;
else
{
for(int i=0; i < Num_Of_Videos; i++)
{
while(Din.good())
{
getline(Din, Video_Array[i]);
Num_Of_Videos++;
cout << "Set_Video says these are the movies" << Video_Array[i] << endl;
}
cout << "Set_Video says these are the movies" << Video_Array[i] << endl;
}
Num_Of_Videos = Num_Of_Videos-2;
}
Din.close();
}
Your loop don't make any sense. Inside the for loop, i is not incremented. So you keep reading into the same element of Video_Array. It's not clear exactly what it is you're trying to do, but the code as written doesn't make much sense. Why do you have two loops?

Resources