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.
Related
I am using Notepad++ with TDM-GCC. My computer is 2Gb RAM Windows 10 32 bit 3.30 GHz. When I execute my simple program, it shows error.
Access is denied.
An attempt was made to execute the below command.
Command: D:\Deane\Github\CPP_Projects\AnalysisName\main.bat
Arguments:
Error Code: 5
Image of the error
I follow this: ShellExecuteEx function always returning error code 5 (C++)
Program's code (if necessary):
/* AnalysisName Program - written by Vo Tran Nha Linh */
#include <iostream> // Input and Output library.
using namespace std;
int main()
{
string name;
cout << "Hello friend! It's nice to meet you, what is your name?" << endl; // Ask the name.
cin >> name; // Input name.
cout << "Hello " << name << ". Your name is interesting." << endl; // Have a greeting.
cout << "Your name has " << name.length() << "letters." << endl; // Show the name's length.
cout << "It starts with " << name.front() << "letter." << endl; // Show the first letter of the name.
cout << "It ends with " << name.back() << "letter." << endl; // Show the last letter of the name.
return 0;
}
But it doesn't active, please give me a help. Thank you very much!
My problem solved!
I miss Visual C++ Redistributable 2008 and 2010.
Moderators please close my topic. Thank you!
Navigate to C:\Program Files (x86)\Notepad++ Right mouse click the Notpad++.exe file click properties & under the compatability Tab UN-TICK run the program as administrator box DONE.
Refer to this link.
this solved it for me:
right click on the file that won't run (in my case a .cmd file)
check the 'Unblock' checkbox next to the remark "This file came from another computer and might be blocked to help protect this computer"
I wanted to start learning how to program, so I asked my math professor if he had a book that I could borrow. He did and so I have been reading a C++ book from ~1994 (it still has a floppy disk :P). Anyway, I made it to a point in it and it sets up a program that calculates y in y=mx+b. Pretty simple, but I decided to try it out and it is not working. I would really like to figure out why it is not working and fix it.
Here is the code for it:
#include <iostream>
using namespace std; //not in the book: added by me after some Googling
int main() {
cout << "Input m: " << flush;
int m;
cin >> m;
cout << "Y-intercept: " << flush;
int b;
cin >> b;
cout << "X coordinate of interest: " << flush;
int x;
cin >> x;
int y;
y = m * x + b;
cout << "y = " << y << "when m = " << m << "; " << "b = " << b << "; x = " << x << endl;
}
edit: Sorry. Forgot to describe what was going on. lol. The program executes properly until it it comes to displaying the final line. After submitting "X coordinate of interest: " the program simply exits. I mean I am no expert in C++, but should the final cout write to the console?
And I know it is really outdated, but I really just want a platform to stand on when I begin to look at the newage languages. The book itself is only about 700 pages, and there is a LOT of explaining in it, so it is not very much code wise. I have probably 10 to 20 700 page pdfs on Java and C#/C++/C all written within the past six years. So I'll be good. Just want a starting point. :) Plus this book explains a lot about how a computer works and certain jargon that some of the newer books just don't.
This is a common windows cmd problem. Either run the program through cmd, type in the executable name, or add getchar or cin >> variable to the end of the program.
Assuming this is in Visual Studio when you run a program with debugging (F5) the console instance is closed automatically. You can either add a input line to the end of the program as others have mentioned or run the program without debugging (Ctrl+F5) and the console window will pause and let you see the output at the end of the programs execution.
friends. I have a problem.
Problem: the computer must pick randomly one string out of an array of 36 strings. If by any chance it picks strings #34 or #35 (the two last ones), it has to draw two more random strings from the same array. I tried a do-while solution, and it "almost" works (see code below).
The randomization works fine - called srand inside main(). There is a forced "x2" draw (for testing reasons), so the computer draws two more strings. These two new random picks are NOT "x2", but still the loop kicks again - but just one more time! This time the computer picks two more "chits", which aren't "x2" either, so, as expected, it returns the "The chits have been drawn" sentence and the function is terminated. Why is the same code running twice with the same results but different if/else behavior? Thank you very much in advance.
string mortalityCalc ()
{
string mortalityChits[36] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","-","-","-","-","x2","x2"};
int mortalityResult;
// mortalityResult = rand() %36;
mortalityResult = 35; // for testing only. Delete afterwards.
string drawnChit = mortalityChits[mortalityResult];
string drawnChit1;
string drawnChit2;
if (drawnChit != "-" && drawnChit != "x2")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'.";
return returnText;
}
else if (drawnChit == "-")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'. No senators died this year.";
return returnText;
}
do
{
cout << "The computer has drawn the 'x2' chit." << endl;
cout << "Two more chits will be drawn.\n" << endl;
mortalityResult = rand() %36;
drawnChit1 = mortalityChits[mortalityResult];
cout << "The first draw is the chit '" << drawnChit1 << "'. ";
mortalityResult = rand() %36;
drawnChit2 = mortalityChits[mortalityResult];
cout << "The second draw is the chit '" << drawnChit2 << "'." << endl;
} while (drawnChit1 == "x2" || drawnChit2 == "x2");
return "The mortality chits have been drawn. The corresponding senators are dead.";
}
UPDATE: Tried running this code isolated from the rest of the program and it behave as expected. So I guess it's important to post what comes before it:
cout << "If you are a lazy bastard, the computer can pick one senator randomly for you.\nAre you a lazy bastard? [y/n]" << endl;
string lazyBastard;
cin >> lazyBastard;
cout << endl;
if (lazyBastard == "y" || lazyBastard == "Y" || lazyBastard == "yes" || lazyBastard == "YES" || lazyBastard == "Yes")
{
mortalityCalc ();
cout << mortalityCalc () << endl;
cout << "Very well. Now, imminent wars become active (Only one of each match)." << endl;
cout << "Get ready for the next phase." << endl;
My guess, from reading some other questions here, is that somehow the cin is messing with the loop behavior, even though they are not related and there's no user input whatsoever in the loop's statements or conditions. Is that possible? If so, why and how to remedy it?
Thank you again.
In the first loop you are forcing an 'x2' so your are entering the do-while loop. The result of the two calls for 'rand())%36' is always 19 and a number between 30 and 34. The point is that the random number generator generates always the same sequence of numbers, if you don't give him a seed 'srand(...)'.
do {
// ...
cout << rand()%36;
// ...
} while( /*...*/ )
See http://ideone.com/zl8ggH
You have to create random numbers and your code does what you expect.
Finally! I thought it would be a stupid thing! I just realized that I called the mortalityCalc() function twice! That's why it was looping twice!
Thanks to all who tried to help!
can anyone help me make this more generalised and more pro?
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// open text file for input:
string file_name;
cout << "please enter file name: ";
cin >> file_name;
// associate the input file stream with a text file
ifstream infile(file_name.c_str());
// error checking for a valid filename
if ( !infile )
{
cerr << "Unable to open file "
<< file_name << " -- quitting!\n";
return( -1 );
}
else cout << "\n";
// some data structures to perform the function
vector<string> lines_of_text;
string textline;
// read in text file, line by
while (getline( infile, textline, '\n' ))
{
// add the new element to the vector
lines_of_text.push_back( textline );
// print the 'back' vector element - see the STL documentation
cout << lines_of_text.back() << "\n";
}
cout<<"OUTPUT BEGINS HERE: "<<endl<<endl;
cout<<"the total capacity of vector: lines_of_text is: "<<lines_of_text.capacity()<<endl;
int PLOC = (lines_of_text.size()+1);
int numbComments =0;
int numbClasses =0;
cout<<"\nThe total number of physical lines of code is: "<<PLOC<<endl;
for (int i=0; i<(PLOC-1); i++)
//reads through each part of the vector string line-by-line and triggers if the
//it registers the "//" which will output a number lower than 100 (since no line is 100 char long and if the function does not
//register that character within the string, it outputs a public status constant that is found in the class string and has a huge value
//alot more than 100.
{
string temp(lines_of_text [i]);
if (temp.find("//")<100)
numbComments +=1;
}
cout<<"The total number of comment lines is: "<<numbComments<<endl;
for (int j=0; j<(PLOC-1); j++)
{
string temp(lines_of_text [j]);
if (temp.find("};")<100)
numbClasses +=1;
}
cout<<"The total number of classes is: "<<numbClasses<<endl;
Format the code properly, use consistent style and nomenclature and throw out the utterly redundant comments and empty lines. The resulting code should be fine. Or “pro”.
Here, I’ve taken the efford (along with some stylistic things that are purely subjective):
Notice that the output is actually wrong (just run it on the program code itself to see that …).
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string file_name;
cout << "please enter file name: ";
cin >> file_name;
ifstream infile(file_name.c_str());
if (not infile) {
cerr << "Unable to open file " << file_name << " -- quitting!" << endl;
return -1;
}
else cout << endl;
vector<string> lines_of_text;
string textline;
while (getline(infile, textline)) {
lines_of_text.push_back(textline);
cout << lines_of_text.back() << endl;
}
cout << "OUTPUT BEGINS HERE: " << endl << endl;
cout << "the total capacity of vector: lines_of_text is: "
<< lines_of_text.capacity() << endl << endl;
int ploc = lines_of_text.size() + 1;
cout << "The total number of physical lines of code is: " << ploc << endl;
// Look for comments `//` and count them.
int num_comments = 0;
for (vector<string>::iterator i = lines_of_text.begin();
i != lines_of_text.end();
++i) {
if (i->find("//") != string::npos)
++num_comments;
}
cout << "The total number of comment lines is: " << num_comments << endl;
// Same for number of classes ...
}
I'm not really sure what you're asking, but I can point out some things that can be improved in this code. I'll focus on the actual statements and leave stylistic comments to others.
cin >> file_name;
To handle file names with spaces, better write
getline(cin, file_name);
int PLOC = (lines_of_text.size()+1);
Why do you claim that there's one more line than there actually is?
if (temp.find("//")<100)
with some complicated comment explaining this. Better write
if (temp.find("//")<temp.npos)
to work correctly on all line lengths.
cout<<"The total number of comment lines is: "<<numbComments<<endl;
Actually, you counted the number of end-of-line comments. I wouldn't call a comment at the end of a statement a "comment line".
You don't count /* */ style comments.
Counting the number of classes as };? Really? How about structs, enums, and plain superfluous semicolons? Simply count the number of occurences of the class keyword. It should have no alphanumeric character or underscore on either side.
Use proper indentation, your code is very difficult to read in its current form. Here is a list of styles.
Prefer ++variable instead of variable += 1 when possible; the ++ operator exists for a reason.
Be consistent in your coding style. If you're going to leave spaces between things like cout and <<, function arguments and the function parantheses do it, otherwise don't, but be consistent. Pick one naming convention for your variables and stick to it. There is a lot about styles you can find on google, for example here and here.
Don't use the entire std namespace, only what you need. User either using std::cout; or prefix all of your cout statements with std::
Avoid needless comments. Everyone knows what ifstream infile(file_name.c_str()); does for example, what I don't know is what your program does as a whole, because I don't really care to understand what it does due to the indentation. It's a short program, so rather than explaning every statement on its own, why not explain what the program's purpose is, and how to use it?
These are all stylistic points. Your program doesn't work in its current form, assuming your goal is to count comments and classes. Doing that is a lot more difficult than you are considering. What if I have a "};" as part of a string for example? What if I have comments in strings?
Don't import the whole std namespace, only things you need from it:
using std::string;
Use a consistent naming convention: decide whether you prefer name_for_a_variable or nameforavariable or nameForAVariable. And use meaningful names: numbComments makes me associate to very different things than would numberOfComments, numComments or commentCount.
If your original code looks like this, I strongly recommend to select a single consistent indentation style: either
if ( ... )
{
...
}
or
if ( ... )
{
...
}
bot not both in the same source file.
Also remove the useless comments like
// add the new element to the vector
This is "only" about the readability of your code, not even touching its functionality... (which, as others have already pointed out, is incorrect). Note that any piece of code is likely to be read many more times than edited. I am fairly sure that you will have trouble reading (and understanding) your own code in this shape, if you need to read it even a couple of months after.
"More professional" would be not doing it at all. Use an existing SLOC counter, so you don't reinvent the wheel.
This discussion lists a few:
http://discuss.techinterview.org/default.asp?joel.3.207012.14
Another tip: Don't use "temp.find("};}) < 100)", use "temp.find("};") != temp.npos;"
Edit: s/end()/npos. Ugh.
I have a variable which holds a score for a game.
My variable is accessible and correct outside of an if statement but not inside as shown below
score is declared at the top of the main.cpp and calculated in the display function which also contains the code below
cout << score << endl; //works
if(!justFinished){
cout << score << endl; // doesn't work prints a large negative number
endTime = time(NULL);
ifstream highscoreFile;
highscoreFile.open("highscores.txt");
if(highscoreFile.good()){
highscoreFile.close();
}else{
std::ofstream outfile ("highscores.txt");
cout << score << endl;
outfile << score << std::endl;
outfile.close();
}
justFinished = true;
}
cout << score << endl;//works
EDIT:
have realised my problem, when I was printing out it looped through many times so I did not see that all of them for the first loop didn't work, hence I thought the others were working when in fact they were not for the first iteration.
This is not a problem relating to the scope of the variable.
It could be several things:
Memory corruption somewhere
Multi threading relating problem
Something else...
Are you sure you are looking at the same iteration where the score value works before and after but not inside? Maybe put some more detailed logging instead of simply outputting the score itself.
Try printing cout << score << "#" << &score << endl; each place you currently print score. This will let you check if you're actually looking at the same variable.
If the addresses are different, you're accidentally shadowing your score variable somewhere - gcc has -Wshadow to catch that.
If the addresses are the same then the variable is getting corrupted somehow. Most debuggers have a memory breakpoint feature, so you can set the debugger to break when the memory in score changes and find the culprit.
With the amount of code you have attached there is nothing to indicate there is a problem in the code. As Brian says it is something else
Can you try this in your debugger and see what happens ? The idea is to simplify the problem as much as possible and try to get the minimal amount of code that replicates the problem.
What does this do ?
cout << score << endl; //works
if(!justFinished)
{
cout << score << endl; // doesn't work prints a large negative number
}
cout << score << endl; //works