how to run PlaySound() function with an string array? - c++

I am trying to get words from a text file and play sounds of those words. I am, somehow succesfull coding the first part but not that sucessful when it comes to play *.wav format sounds.
I do get words from text file and add them into a string array. but I could not manage to use PlaySound() function with that array. here is the code
i = 0;
while (i < count) {
cout << "now playing:" << str[i] << endl;
i++;
bool played = PlaySound(TEXT("-.wav"), NULL, SND_SYNC);
cout << "played ?" << played << endl;
}
All i want to do is replace that "-.wav" with my current str[i] index. The indexs are 4 words for now. Can-You-Hear-Me. These words must be in playsound function. I hope my eng is clear enough. Thx

Related

How to I update a pre-existing leaderboard text file, making sure it's sorted?

First of I'd like to thank you all in advance for taking your time reading and helping me with my problem. I'm in no way shape or form an expert at c++, I'm not even good. I started programming in c++ 2 months ago and I find it quite harder than python, for a second experience with programming languages.
So I'm making this game for my programming class and I have to have a leaderboard text file with all the winners of a certain level. I set it up so the file always has the same format for time, name like this.
I've been trying to figure out how to sort the leaderboard entries by time and then by name. I thought of reading the file from line 3 and beyond but that doesn't seem to work. I moved on to what seems a better way of doing it which is to read the whole leaderboard discarding the first 2 lines, store it line by line on a vector, sorting the vector then and wiping the file by opening it in trunc mode but for some reason the file doesn't get wiped, it just keeps on adding more and more entries. I wan't it to add the sorted lines (vector) to the leaderboard one by one up until 10 entries are hit. Can someone help me? Here's a code sniped with the function I'm using to update the leaderboard
// Function to check if MAZE_XX_WINNERS.txt exists, if not creates it
void makeLeaderboard(string maze_name, string formated_time){
string winner_name, filename = maze_name.substr(0,7) +"_WINNERS.txt";
while(true){
// If MAZE_XX_WINNERS.txt file exists
if(ifstream(filename)){
// Open MAZE_XX_WINNERS.txt file in append mode
fstream leaderboard(filename, fstream::app);
// Ask for player name
cout << "Type your name (max 15 characters): ";
getline(cin, winner_name);
// If name is valid
if(isValidName(winner_name) && winner_name.length() <= 15){
string line;
vector<string> lb_entries;
int n_line = 0;
// Append to the end of the file
leaderboard << formated_time << " - " << winner_name << endl;
// Store all leaderboard entries in a vector
while(!leaderboard.eof()){
if(n_line >= 2){
getline(leaderboard, line);
lb_entries.push_back(line);
}
n_line++;
}
leaderboard.close();
//Everything works up until here, past here it doesn't do anything I want it to do
// Sort the leaderboard entries first by time, then by name
sort(lb_entries.begin(), lb_entries.end());
// Check if leaderboard has more than 10 entries to delete those past the limit
if(lb_entries.size() > 10){
// Truncates the vector from the 10th position forward
lb_entries.erase(lb_entries.begin()+9, lb_entries.end());
}
// Reopens the file in truncation mode to delete pre-existing leaderboard
leaderboard.open(filename, fstream::trunc);
// Format the file to have a table like shape
leaderboard << "| TIME - NAME |" << endl;
leaderboard << "------------------------------" << endl;
// Updates leaderboard
for(string entry : lb_entries){
leaderboard << entry << endl;
}
leaderboard.close();
break;
}
// If name not valid
else if(isValidName(winner_name) && winner_name.length() > 15){
cerr << endl << "Name has more than 15 characters! Please retry." << endl << endl;
}
else{
cerr << endl << "Not a valid name input!" << endl << endl;
}
}
// If file doesn't exist
else{
// Attempt to create the file
cout << "Creating leaderboard..." << endl;
ofstream leaderboard(filename);
// Check if file was created
if(!leaderboard){
cerr << "File could not be created" << endl;
}
else{
// Format the file to have a table like shape
leaderboard << "| TIME - NAME |" << endl;
leaderboard << "------------------------------" << endl;
leaderboard.close();
}
}
}
}
You need to break your problem down. What I would do is create a class that represents the LeaderBoards. It would actually consist of two classes. You could do one as an inner class of the others, but let's keep them separate:
class Leader {
public:
std::string time;
std::string name;
};
class LeaderBoard {
public:
std::vector<Leader> leaders;
void readFromFile(std::string fName);
void sort();
void writeToFile(std::string fName);
};
At that point, you need to implement three functions. None of them are very long.
void LeaderBoard::readFromFile(std::string fName) {
std::ifstream file(fName);
std::string line;
// skip the header
file.getline(line);
file.getline(line);
// Read the rest of the file.
while (file.getline(line)) {
// You'll need to parse the line into its parts
Leader leader(from the parts);
leaders.push_back(leader);
}
}
Yeah, I left some magic for you.
The write method would be very simple and just use an ofstream instead of an ifstream.
The sort method -- you can do a google for "c++ sort vector of objects" and get LOTS of examples.
In general, ALL programming can be broken down into smaller steps. If you're getting overwhelmed, break it down. This is one of the reasons you use an object-oriented language. If you don't know how to do something, create a class for it, then put methods in it for the smaller steps.
Then just figure out how to do small parts at a time. First: get data. Then print it out so you're sure you've got what you need.
If your code is more than about a screen or so, you're doing too much in one method. That's not an absolute, but at your level of coding, it's definitely true.
Small, tight methods. Small, tight methods are easier to write. Then string them together.
In this case:
Read the data
Sort the data
Write the data.
Each of these is easy to test individually.

Baby names popularity program

I have to write a program that allows the user to input a name from the keyboard. The program should then read from the file and search for matching name among the girls and boys. If a match is found it should output the rank of the name. The program should also indicate if there is no match.
Here is my program :
ifstream fin;
fin.open( "/Users/fashiontekk/Downloads/Assignment 3 Instructions/babyNames2017.dat" );
string nameInput;
string boyName;
string girlName;
int rank= 0;
int boyRank= 0;
int girlRank =0;
cout << " Which name would you like to check? < no space in names please > " << endl;
cin >> nameInput;
fin >> boyName;
fin >> girlName;
rank++;
cout << " After going through an extensive search here is what we found out - " << endl;
if (nameInput == boyName) {
cout << nameInput << " is ranked " << rank << " in popularity among boys. " << endl;
boyRank = rank;
}
if (nameInput == girlName) {
cout << nameInput << " is ranked " << rank << " in popularity among girls. " << endl;
girlRank = rank;
}
if (boyRank < 1 || boyRank > 1000) {
cout << nameInput << " is not ranked among the top 1000 boys name. " << endl;
}
if (girlRank < 1 || girlRank > 1000) {
cout << nameInput << " is not ranked among the top 1000 girls name. " << endl;
}
cout << " Hope that is the result you were looking for ... Ending program. " << endl;
fin.close();
return 0;
}
However, my output window says : Which name would you like to check? < no space in names please >
Program ended with exit code: 0Liam
After going through an extensive search here is what we found out -
Liam is ranked 1 in popularity among girls.
Liam is not ranked among the top 1000 boys name.
Hope that is the result you were looking for ... Ending program.
I tried to type in Liam which the most popular boys name according to the file provided. I feel like my coding is right however I can't spot the error.
It is my first year in Computer Science and I don't can't find my mistake.
OK, we've all been there at some point. You need to work on your debugging skills — you're gonna need them. In particular, spend some time learning to use gdb or whatever debugger you have available. A good debugger will let you step through a program a line at a time, watch variables, and generally checkout every possible thing that could be a problem.
So let's take a look at your code with an eye toward debugging it. It's handy that the message that's emitted comes right up near the top of the program — that really narrows down the places where you could be going wrong. Here's the first part of your program:
ifstream fin;
fin.open( "babyNames2017.dat" );
if (!fin) {
cout << " File not processed ";
return 0;
}
So, the first line just declares the variable for your input file. There's not much that can go wrong there. The next line opens the file... hmmm... I'm not sure if that might be a problem or not, so let's stick a pin in it for now and keep going. The next line, if (!fin) {, is a condition that only succeeds if !fin is true, which means that fin must evaluate to false to enter this block. And it clearly does enter this block, because that's the part of the code that emits the "File not processed" message. So fin must be 0, right? OK, so how can fin possibly be 0?
I don't have the C++ iostreams documentation handy, but you should go look up what that fin.open(...) call does if it fails. Given the way you've written the code, it looks very much like you'd expect failure to set fin to 0, right? So how can that call fail? Well, for starters, you're only supplying the file name... the working directory when you run the program might be set to something you don't expect, so the file isn't found. Or the file name might not match the name of the actual file. Remember that some file systems are case sensitive, and if you're working with such a file system then the open call will fail if the file is just named babynames2017.dat or BabyNames2017.dat or anything else that doesn't exactly match your file.

Making strcmp() case insensitive without using strcmpi() (C++)

I am working a program that searches for a string (in this case a name) in a file. I wanted the program not to be case sensitive but strcmp is. I was thinking to convert bot the file and user input to lowercase. But that would be inefficient. Any other suggestions to overcome this?
This is a fraction of code to just get an idea of the program
cout << "\n Enter the Guests name: ";
cin.getline(look_4_person, 256); //name that is being looked up
cout << "\n Searching... \n";
while(!name_file.eof())
{
++place;
name_file.getline(person,255);
if(strcmpi (person,look_4_person)==0)
{
found=place;
}
}
cout << "\n" << look_4_person << " is number " << found <<
" on the list \n";
was thinking to convert bot the file and user input to lowercase. But that would be inefficient. Any other suggestions to overcome this?
To re-think this.
This is a typical way of dealing with case sensitiveness. I mean converting both strings (file name and user input) to lowercase.
This takes O(n), where n = max(filename.size, userInput.size).
As for performance, the filename and the user input are usually tiny data, thus I am pretty sure that converting them to lower case, will be definitely not be the bottleneck of your algorithm.
while(!name_file.eof()){
++place;
name_file.getline(person,256);
for(i=0; i<200; i++)
{
person[i] = tolower(person[i]); //changes to lower case to compare
}
if(strcmp (person,look_4_person)==0){ //compares
found=place;
}

removing multiple spaces in c++ from string

I have the following code to open a file and read the data from it, then take the relavent part and print it to screen.
char* search = "model name";
int Offset;
string Cpu;
ifstream CpuInfo;
CpuInfo.open ("/proc/cpuinfo");
if(CpuInfo.is_open())
{
while(!CpuInfo.eof())
{
getline(CpuInfo,Cpu);
if ((Offset = Cpu.find(search, 0)) != string::npos)
{
//cout << "found '" << search << " " << line << endl;
break;
}
}
CpuInfo.close();
}
Cpu.replace (0,13,"");
cout << Cpu
This usually outputs the type of CPU your using, but one problem is that some people have various spaces inbetween the words that it prints out.
My question is how to remove all the spaces from inbetween the words. They can of random ammount and aren't always present.
Thank you in advance.
Since your question states: "how to remove all the spaces from inbetween the words":
You can use std::remove_if from the standard <algorithm> library in addition to std::isspace:
std::string mystring = "Text with some spaces";
std::remove_if(mystring.begin(), mystring.end(), std::isspace);
This now becomes:
Textwithsomespaces
REFERENCES:
http://en.cppreference.com/w/cpp/algorithm/remove

Parse int and string

Hi I'm not sure if this is the right place to ask this question.
Anyway I have written this code to parse a molecule formula and split it into atoms and amount of each atoms.
For instance if I input "H2O" I will for the atom array get {"H", "O"} and in the amount array I will get {2, 1}. I haven't taken account for amount that is larger than 9, since I don't think there are molecule which can bind to something that is larger than 8.
Anyway I'm quite newbie, so I wonder if this piece of code can be made better?
string formula = "H2O";
int no, k = 0, a = 0;
string atom[10];
int amount[10];
bool flag = true;
stringstream ss(formula);
for(int i = 0; i < formula.size(); ++i)
{
no = atoi(&formula[i]);
if(no == 0 && (flag || islower(formula[i]) ) )
{
cout << "k = " << k << endl;
atom[k] += formula[i];
flag = false;
cout << "FOO1 " << atom[k] << endl;
amount[a] = 1;
}
else if(no != 0)
{
amount[a] = no;
cout << "FOO2 " << amount[a] << endl;
a++;
flag = true;
k++;
}
else
{
k++;
a++;
atom[k] = formula[i];
cout << "FOO3 " << atom[k] << endl;
amount[a] = 1;
flag = false;
}
cout << no << endl;
}
Have you considered an approach with regular expressions? Do you have access to Boost or TR1 regular expressions? An individual atom and its count can easily be represented as:
(after edits based on comments)
([A-Z][a-z]{0,2})([0-9]*)
Then you just need to repeatedly find this pattern in your input string and extract the different parts.
There are many potential improvements that could be made, of course. But as a newbie, I guess you only want the immediate ones. The first improvement is to change this from a program that has a hard coded formula to a program that reads a formula from the user. Then try testing yout program by inputting different formulae, and check that the output is correct.
What if you modified it to be like this algorithm? This would maybe be less code, but would definitely be more clear:
// while not at end of input
// gather an uppercase letter
// gather any lowercase letters
// gather any numbers
// set the element in your array
This could be implemented with 3 very simple loops inside of your main loop, and would make your intentions to future maintainers much more obvious.