I am receiving the following debug error when attempting to run the first part of my program:
Debug Error!
Program:
...\user\desktop\PunchLineProgram\Debug\PunchLineProgram.exe
Module:
...\user\desktop\PunchLineProgram\Debug\PunchLineProgram.exe
File:
Run-Time Check Failure #3 - T
(Press Retry to debug the application)
I am attempting to have the user select whether they want to hear a joke, running and if\else statement that will output a message to the user, based on their response. If I comment out these statements, I do not receive the error when attempting to run the program. I know I'm probably missing something simple, as I am a novice. Here is the code that I have so far:
/*Include Section*/
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <cctype>
/*Namespace Section*/
using namespace std;
/*Function Prototypes Section*/
void displayAllLines(ifstream &infile);
void displayLastLine(ifstream &infile);
/*Main section: this is the entry point of the program, which controls the flow of execution*/
int main()
{
string file1;
string file2;
ifstream joke;
ifstream punchline;
int decision;
char y;
char n;
cout << "*******************************************************************************" << endl;
cout << setw(48) << "Punchline Program" << endl;
cout << "*******************************************************************************" << endl;
cout << endl;
cout << "Welcome to the Punchline Program!" << endl;
cout << "Are you ready to hear a joke? (y or n): ";
cin >> decision;
if (decision == y)
{
cout << "Great! Let's get started!" << endl;
}
else if (decision == n)
{
cout << "Ah, no sense of humor, I see. Time to make like a tree and leaf (queue rimshot)!" << endl;
}
system("PAUSE");
}
Any help would be greatly appreciated!
When comparing to char you should use '':
char answer
if (answer == 'y') { *//this only checks for LOWER case y*
cout << "You selected Yes" << endl;
}
when comparing to a string use ""
int/float/double... you can just use the variable.
Besides that, your decision variable as int when it should be char, and you don't need char y nor n. (you yourself never even used it in that code)
I'd suggest looking up c++ tutorials, most show and explain the different between char/string, ' and ".
Related
I'm trying to make this kina guess game on C++, I'm a beginner and still learning.
What I'm trying to achieve is a guessing game of two const names, is very simple without errors but it's not working after I enter something. it should report until I find the correct name. Please also I don't want to change the structure of the code, just find why isn't working.
#include <iostream>
#include <string>
using namespace std;
struct Vlerat {
string guess01 = "Resul";
string guess02 = "Rejan";
int numruesi = 0;
};
int main() {
Vlerat funksioni;
string nameGuess;
int nameOkay = 0;
cout << "Gjej njerin prej dy emrava te fshehura." << endl;
cout << "Ndihm: Fillojn me Shkronjen 'R', dhe pas asaj vjen edhe nje shkronj 'e'" << endl;
do {
cout << "Shkruaj Emrin > "; cin >> nameGuess;
if (nameGuess == funksioni.guess01){
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
if (nameGuess == funksioni.guess02) {
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
funksioni.numruesi++;
} while(nameOkay = 0);
}
You should change while(nameOkay = 0); to while(nameOkay == 0);.
Because = is an assignment, but == is operator of comparing (equality)
Read about it here
And here
I do not know how to declare "random" in the parentheses for "int main()," and need help. (I am a beginner in C++)
Please take a look at my code, try it out, and please notify me with an answer when you think you know how to solve this problem. It'd mean a lot to me. Thanks! Meanwhile, I will keep trying to solve the problem myself as well.
Note: I am using Code::Blocks if you want to be specific.
The error is on Line 7/9 of my code.
Here is my updated code below:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
int rn = random() % 21; // generates a random int from 0 to 20
// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;
while (u != rn) // Calculates the answer that you give
{
// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}
// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;
}
// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}
Here's the updated compiler error:
||=== Build: Debug in Guess The Number (compiler: GNU GCC Compiler) ===|
C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp||In function 'int main()':|
C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp|12|
error: 'randomize' was not declared in this scope|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Remove the semicolon near main, the compiler is telling you exactly what the issue is:
int main ();
Should be
int main ()
Your code will also not compile even after fixing this because you have not declared the std namespace. You can put this line at the top for now using namespace std; but it is bad practice. You should declare it manually using the scope resolution operator.
And a number of other issues as already mentioned in the comments above, make sure to read the compiler output thoroughly because it tells you what line is causing the issue.
Your code should look like:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
int rn = random() % 21; // generates a random int from 0 to 20
// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;
while (u != rn) // Calculates the answer that you give
{
// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}
// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;
}
// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}
Someone else got to it. There are no semicolons after signatures to methods like main().
One other thing not mentioned, I'm guessing you want
while (u != rn)
Also, be careful of the difference in "=" and "==".
BTW -- Welcome to C++!!!
a little more portable version (doesn't use conio.h) which lets the computer play against himself:
#include <iostream>
#include <cstdlib>
#include <ctime>
int get_random_in_range(int min, int max)
{
return std::rand() % (max - min) + min;
}
// returns 0 if user guessed right, negative value if user
// guessed too small, positive if user guessed too big
int check_user_guess(int guess, int my_secret)
{
return guess - my_secret;
}
int main ()
{
int my_guess = get_random_in_range(1, 10);
std::cout << "I think of " << my_guess << std::endl;
std::cout << "Please guess my number: ";
int user_guess = get_random_in_range(1, 10);
std::cout << user_guess << std::endl;
while (check_user_guess(user_guess, my_guess) != 0)
{
std::cout << "You guessed " << user_guess << std::endl;
if (check_user_guess(user_guess, my_guess) > 0)
{
std::cout << "You guessed too big!" << std::endl;
}
else if (check_user_guess(user_guess, my_guess) < 0)
{
std::cout << "You guessed too small!" << std::endl;
}
std::cout << "Please guess again: ";
user_guess = get_random_in_range(1, 10);
std::cout << user_guess << std::endl;
}
std::cout << std::endl << "You guessed it right!";
}
try it here: http://coliru.stacked-crooked.com/a/5bf0b9201ef57529
Sorry guys forewarning I suck at coding but have a big project and need help!
Input: A complete Sentence.
Output: The sorted order (ASCii Chart Order) of the sentence (ignore case.)
Output a histogram for the following categories:
1) Vowels
2) Consonants
3) Punctuation
4) Capital Letters
5) LowerCase Letters
I have no clue what to even do
Since you are vague in what your issue is, I recommend the following process:
Review Requirements
Always review the requirements (assignment). If there are items you don't understand or have the same understanding as your Customer (instructor), discuss them with your Customer.
Write a simple main program.
Write a simple main or "Hello World!" program to validate your IDE and other tools. Get it working before moving on. Keep it simple.
Here's an example:
#include <iostream>
#include <cstdlib> // Maybe necessary for EXIT_SUCCESS.
int main()
{
std::cout << "Hello World!\n";
return EXIT_SUCCESS;
}
Update program to input text & validate.
Add in code to perform input, validate the input and echo to the console.
#include <iostream>
#include <cstdlib> // Maybe necessary for EXIT_SUCCESS.
#include <string>
int main()
{
std::string sentence;
do
{
std::cout << "Enter a sentence: ";
std::getline(cin, sentence);
if (sentence.empty())
{
std::cout << "\nEmpty sentence, try again.\n\n"
}
} while (sentence.empty());
std::cout << "\nYou entered: " << sentence << "\n";
// Keep the console window open until Enter key is pressed.
std::cout << "\n\nPaused. Press Enter to finish.\n";
std::cin.ignore(100000, '\n');
return EXIT_SUCCESS;
}
Add functionality, one item at a time and test.
Add code for one simple requirement, compile and test.
After it works, make a backup.
Repeat until all requirements are implemented.
For ordering the string you can use standard c qsort function. For counting vowels, consonants, punctuation... you need a simple for loop.
Here is a working example:
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int cmp(const void* pc1, const void* pc2)
{
if(*(char*)pc1 < *(char*)pc2) return -1;
if(*(char*)pc1 > *(char*)pc2) return 1;
return 0;
}
void main(int argc, char* argv[])
{
char pczInput[2000] = "A complete sentence.";
cout << endl << "Input: '" << pczInput << "'";
qsort(pczInput, strlen(pczInput), sizeof(char), cmp);
cout << endl << "Result: '" << pczInput << "'";
int iCapital = 0;
int iLowerCase = 0;
int iPunctuation = 0;
int iVowels = 0;
int iConsonants = 0;
for(unsigned int ui = 0; ui < strlen(pczInput); ++ui)
{
if(isupper(pczInput[ui])) ++iCapital;
if(islower(pczInput[ui])) ++iLowerCase;
if(ispunct(pczInput[ui])) ++iPunctuation;
if(strchr("aeiouAEIOU", pczInput[ui]) != NULL) ++iVowels;
if(strchr("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ", pczInput[ui]) != NULL) ++iConsonants;
}
cout << endl << "Capital chars: " << iCapital;
cout << endl << "Lower case chars: " << iLowerCase;
cout << endl << "Punctuation chars: " << iPunctuation;
cout << endl << "Vowels chars: " << iVowels;
cout << endl << "Consonants chars: " << iConsonants;
cout << endl;
}
Note that I used C standard functions for counting capital, lower case and punctuation, and I had to use strchr function for counting vowels and consonants because such functions are missing in standard C library.
The output of the program is:
Input: 'A complete sentence.'
Result: ' .Acceeeeelmnnopstt'
Capital chars: 1
Lower case chars: 16
Punctuation chars: 1
Vowels chars: 7
Consonants chars: 10
I am about to write a program which asks the user if they want to "search or convert" a file, if they choose convert, they need to provide the location of the file.
I do not know why the program shows the address of the file instead of opening it.
Here is my first approach:
#include <fstream>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
char dateiname[64], kommando[64];
ifstream iStream;
cout << "Choose an action: " << endl <<
" s - search " << endl <<
" c - convert" << endl <<
" * - end program" << endl;
cin.getline(kommando,64,'\n');
switch(kommando[0])
{
case 'c':
cout << "Enter a text file: " << endl;
cin.getline(dateiname,64,'\n');
iStream.open("C://users//silita//desktop//schwarz.txt");
case 's': break;
case '*': return 0;
default:
cout << "Invalid command: " << kommando << endl;
}
if (!iStream)
{
cout << "The file " << dateiname << " does not exist." << endl;
}
string s;
while (getline(iStream, s)) {
while(s.find("TIT", 0) < s.length())
s.replace(s.find("TIT", 0), s.length() - s.find("TIT", 3),"*245$a");
cout << iStream << endl;
}
iStream.close();
}
At first you can't compare c-strings using ==. You must use strcmp(const char*, const char*). More info about it you can find there: http://www.cplusplus.com/reference/cstring/strcmp/
For example: if (i == "Konvertieren") must become if(!strcmp(i,"Konvertieren"))
As mentioned in Lassie's answer, you can't compare strings in this way using c or c++; just to flesh it out, however, I'll explain why.
char MyCharArr[] = "My Character Array"
// MyCharArr is now a pointer to MyCharArr[0],
// meaning it's a memory address, which will vary per run
// but we'll assume to be 0x00325dafa
if( MyCharArr == "My Character Array" ) {
cout << "This will never be run" << endl;
}
Here the if compares a pointer (MyCharArr) which will be a memory address, ie an integer, to a character array literal. Obviously 0x00325dafa != "My Character Array".
Using cstrings (character arrays), you need to use the strcmp() function which you will find in the cstring library, which will give you a number telling you "how different" the strings are, essentially giving the difference a numerical value. In this instance we are only interested in no difference, which is 0, so what we need is this:
#include <cstring>
using namespace std;
char MyCharArr[] = "My Character Array"
if( strcmp(MyCharArr,"My Character Array")==0 ) {
// If there is 0 difference between the two strings...
cout << "This will now be run!" << endl;
}
While you are not doing so in your question, If we were using c++ strings rather than character arrays, we would use the compare() method to similar affect:
#include <string>
using namespace std;
string MyString = "My C++ String"
if( MyString.compare("My C++ String")==0 ) {
// If there is 0 difference between the two strings...
cout << "This will now be run!" << endl;
}
EDITED for full code
I am trying to make a text based rpg game because im really bored and want to put my c++ "skills" at test xd.
But i am having a problem with the functions srand and rand, the function to generate random numbers.
What i want do achieve, is to let the RNG decide the next action of the game. I.e :
#include <iostream>
#include <windows.h>
#include <string>
#include "conio.h"
#include <time.h>
using namespace std;
void GetRandom();
int main()
{
int x;
string name;
srand(time(NULL));
cout << "welcome to adventurers world!" << endl;
cout << "you wake up on an island far far away and you don't know where you are" << endl;
Sleep(2000);
cout << "Please enter the name of your adventurer" << endl;
getline(cin, name);
cout << "hello " << name << endl;
Sleep(1000);
cout << "where would you like to go, " << name << " ?" << endl;
Sleep(1000);
cout << "1. waddle around the beach\n2. go to the cave straight ahead\n3. go into the forest" << endl;
cin >> x;
if(x==1)
{
cout << "you waddle abit around on the beach, and you suddenly " << random;
}
_getch();
}
void random()
{
srand(time(NULL));
int randnumber = rand() % 2 + 1;
randnumber = randnumber;
if(randnumber == 1)
{
cout << "you encounter a mudcrab" << endl;
}
else if (randnumber == 2)
{
cout << "you find a stick" << endl;
}
}
What i want do achieve here is, if the random number generated is 1 do (randnumber == 1) and if it is 2, do (randnumber == 2)
but instead it just gives me a hexidecimal as output.
is my code properly written? am i using the right expression for srand, calculation w/e.
And is this even possible to do? or do i have to write it out manually what will happen next, which wont make it as much a dynamic game.
thanks for your help and time
At the moment, you're not calling the function random, you're displaying its address. Try this:
if(x==1)
{
cout << "you waddle abit around on the beach, and you suddenly ";
random();
}
Don't seed the random generator with the time each time you need a random number. Unless the usage is a long time between (more than a second), that will set the seed to the same value.
Don't name your function random(). That will make the random() function inaccessible. It probably should be choose_random_object() or something like that.
Seed the random number generator once when the program begins, and only reseed it if you need to repeat the random numbers (unlikely in a situation such as this).
Calling a function should return a value which is useful—which yours is not. Call a procedure (a function which does not return a value) for its side-effects, such as printing out a word.
Here's what your code should look like. The comments give an explanation of the changes.
srand(time(NULL)); // srand() needs only to be called once in the beginning.
if(x == 1)
{
cout << "you waddle abit around on the beach, and you suddenly ";
GetRandom(); // call the function to output what you need.
}
void GetRandom() // change the name of the function.
{
int randnumber = rand() % 2 + 1;
// no need for: randnumber = randnumber;
if(randnumber == 1)
{
cout << "you encounter a mudcrab" << endl;
}
else // no need for else if since the random # cannot be anything else but 2
{
cout << "you find a stick" << endl;
}
}