I am writing a music program that will read (from a separate file) a guitar chord and display it to the the user. The format of the separate text file is as follows:
A
|--0--|
|--2--|
|--2--|
|--2--|
|--0--|
|--x--|
B
|--2--|
|--4--|
|--4--|
|--4--|
|--2--|
|--x--|
C
|--0--|
|--1--|
|--0--|
|--2--|
|--3--|
|--3--|
etc...
I want the user to be able to search for a specific chord in the file and I would like some help on how I can make that happen. I don't have much experience with searching through files. My code so far is below. Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
usingnamespace std;
int main()
{
cout << "\n -- Welcome to Chord Finder --" << endl << endl;
bool program_running = true;
int user_menu1;
int user_chordSelection;
ifstream myfile("chords.txt");
while(program_running == true)
{
user_menu1 = 0;
cout << " What would you like to do: " << endl
<< " 1.) Search for a chord" << endl
<< " 2.) List all the chords in the library" << endl
<< " 3.) Show the major scale for a chord" << endl
<< " 4.) List the contents of the dictionary" << endl
<< " 5.) Exit the program" << endl
<< " \n Your Selection: ";
cin >> user_menu1;
cout << endl;
// cout << user_menu1;
if (user_menu1 == 1)
{
cout << "What chord would you like to see: ";
cin >> user_chordSelection;
}
if (user_menu1 == 2)
{
cout << "THIS FEATURE IS NOT YET AVAILABLE" << endl;
}
if (user_menu1 == 3)
{
cout << "THIS FEATURE IS NOT YET AVAILABLE" << endl;
}
if (user_menu1 == 4)
{
// display the contents of the chord dictionary
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
}
if (user_menu1 == 5)
{
myfile.close();
cout << "Thank you for using my program. Goodbye." << endl;
program_running = false;
}
}
return 0;
}
The best way to deal with this is to create a struct (or class) that represents a chord. At program startup you want to read the file and populate an array of chord structs. Perhaps something like this:
1 2 3 4 5 6 7
struct chord
{ string chordname;
int finger[6];
};
chord chords[50];
int num_chords = 0;
You can search the file on each request, but that is generally considered inefficient. Searching the array is much easier.
You have a problem with option 4. It won't work more than once since it closes the file. In general if you're going to read the file more than once, you have to be cognizant of your position in the file and reposition to the beginning or close and reopen the file.
Oh ok. Thanks! That seems like a pretty easy solution. I don't know why I didn't think of that. I just noticed that option 4 closes the file. I also don't have any idea why that's in there... I make alot of little careless mistakes apparently.
Anyway, thanks a bunch for your help and have a wonderful day.