I'm writing a basic random number guessing game, and I'm trying to perfect it a bit when it comes to entering illegal characters, and as long as numbers outside of the range 1-100 are entered the program tells the user and the user gets to redo it, same goes with letters. However, if you enter 23x5 you end up getting double error messages, you get both the letter and a too high/too low depending on the random number. How do I sort it out so that this entry would go under the letter error message as well?
Here's my code:
Header.h
#ifndef HEADER_H
#define HEADER_H
int nGuessedNumber;
int nNumberOfGuesses = 1;
int nRandomNumber;
int UserInput();
#endif
Source.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
extern int nGuessedNumber;
int UserInput()
{
while(!(cin >> nGuessedNumber))
{
cin.clear();
while(cin.get() != '\n'){}
cout << "I asked for a number between 1 and 100.\n";
}
return nGuessedNumber;
}
main.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Header.h"
using namespace std;
int main()
{
srand(time(0));
nRandomNumber = rand() % 100 + 1;// sets random number between 1 and 100
cout << "Guess a number from 1 too 100: " << endl;
UserInput();
while (nGuessedNumber != nRandomNumber)
{
if ((nGuessedNumber < 1) || (nGuessedNumber > 100))
{
cout << "Oi! Between 1 and 100!\n";
UserInput();
}
else
{
if (nGuessedNumber < nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber < nRandomNumber; nNumberOfGuesses++)
{
cout << "Too low, try again!" <<endl;
UserInput();
}
}
else if (nGuessedNumber > nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber > nRandomNumber; nNumberOfGuesses++)
{
cout << "Too high, try again!"<< endl;
UserInput();
}
}
}
}
if (nGuessedNumber == nRandomNumber)
{
cout << "Congratulations! " << nGuessedNumber << " is correct!" << endl;
cout << "You guessed " << nNumberOfGuesses << " times." << endl;
}
system("PAUSE");
return 0;
}
Read whole lines from std::cin and parse them individually using std::istringstream:
int UserInput()
{
std::string line;
while (getline(std::cin, line)) {
std::istringstream is(line);
if (is >> nGuessedNumber) {
...
return nGuessedNumber;
} else {
...
}
}
}
Related
This is one of my homework and I keep running into seg fault after the cin while loop, can anybody tell what did I do wrong? I have not learn map yet so I can't do that. One of my thought is that it went into seg fault because I was comparing the two string elements inside the vector, what is the way to do that properly?
#include <chrono>
#include <climits>
#include <cfloat>
#include <limits>
#include <cassert>
#include <exception>
#include <cctype>
#include <string>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <regex>
#include <vector>
using namespace std;
int main()
{
vector<string> word_input;
vector<int> word_count;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
while (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
if (word != word_input.back())
{
word_input.push_back(word);
word_count.push_back(1);
}
else
{
word_count.push_back( word_count.back() + 1);
}
}
int count =word_count.back();
// Compare the input words
// and output the times of every word compared only with all the words
for (int i = 0; i != count; ++i)
{
int time = 0;
for (int j = 0; j != count; ++j)
{
if (word_input[i] == word_input[j])
++time;
}
std::cout << "The time of "
<< word_input[i]
<< " is: "
<< time
<< endl;
}
inputFile.close();
return 0;
}
The strategy you are using is fraught with problems. A simpler approach would be to use a std::map<std::string, int>.
int main()
{
std::map<std::string, int> wordCount;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
if (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
// --------------------------------------------------------------
// This is all you need to keep track of the count of the words
// --------------------------------------------------------------
wordCount[word]++;
}
for ( auto const& item : wordCount )
{
std::cout << "The time of "
<< item.first
<< " is: "
<< item.second
<< std::endl;
}
inputFile.close();
return 0;
}
I am getting several errors within my code and as I am new to C++ am struggling to figure out what I am doing wrong and what the solution would be. I have googled around a fair bit but nothing I have found has made sense so if anyone can give me some help it would be amazing so that I can learn from this.
The errors are all on line 23 which is search(token);
Error C2672 'search': no matching overloaded function found TakeTwo d:\desktop\twittersearch\taketwo\taketwo\taketwo.cpp 23
Error C2780 '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2)': expects 4 arguments - 1 provided TakeTwo d:\desktop\twittersearch\taketwo\taketwo\taketwo.cpp 23
Error C2780 '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2,_Pr)': expects 5 arguments - 1 provided TakeTwo d:\desktop\twittersearch\taketwo\taketwo\taketwo.cpp 23
The code:
#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string token;
int main()
{
int menu_choice;
cout << "Main Menu:\n";
cout << "1. Search for \"winner\" \n";
cout << "Please choose an option: ";
cin >> menu_choice;
if (menu_choice == '1') {
token == "winner";
search(token);
} else {
cout << "\nPlease enter a valid option\n";
system("Pause");
system("cls");
main();
}
return 0;
}
void search(string &token)
{
ifstream fin;
fin.open("sampleTweets.csv");
if (fin.is_open())
{
cout << "File opened successfully" << "\n";
}
else {
cout << "Error opening file" << "\n";
}
string line;
while (getline(fin, line)) {
if (line.find(token) != string::npos) {
int n = line.find(",");
char c;
line[n] = ' '; //Changes the comma spacing
line.erase(remove_if(line.begin(), line.end(), [](char chr) { return chr == '\"' || chr == '\'' || chr == ','; }), //Removes the characters " ' and , from the strings
line.end());
line.erase(n + 1, 1); //Removes the 'b' from the beginning of each tweet
cout << line << endl;
}
}
fin.close();
char anykey;
cout << "press any key";
cin >> anykey;
return;
}
The perils of using namespace std;. Since you never declare or define the search function before it's used, the compiler is assuming you mean std::search which is part of the <algorithm> header. Making sure to declare your function before it's used will fix the error in this case.
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string token;
// Forward declare search before first use
void search(string &token);
int main()
{
int menu_choice;
cout << "Main Menu:\n";
cout << "1. Search for \"winner\" \n";
cout << "Please choose an option: ";
cin >> menu_choice;
if (menu_choice == '1') {
token == "winner";
search(token);
}
else {
cout << "\nPlease enter a valid option\n";
system("Pause");
system("cls");
main();
}
return 0;
}
I need to do some error handling in c++ that corrects user input if it's a letter or a string. I need to use .at(), .length(), and atoi to handle this. I'm not sure how/where to implement those is the problem.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace std;
int main() {
srand(time(0));
int number;
number = rand() % 50 + 1;
int guess;
int x;
for (x = 5; x > 0; x--) {
cout << "Guess my number, it's between 0-50. You have 5 guesses: ";
cin >> guess;
if (guess < number){
cout << "Your guess was too low" << endl;
}
else if (guess > number){
cout << "You guess was too high" << endl;
}
else {
cout << "You're exactly right!" << endl;
break;
}
} while (guess != number){
break;
}
return 0;
}
The best approach to input validation is to write a function that reads into a std::string, checks whatever is needed, and only returns a value when it passes the tests:
int get_value() {
std::string input;
int value = -1;
while (value < 0) {
std::cout << "Gimme a value: ";
std::getline(std::cin, input);
try {
value = std::stoi(input);
} catch(...) {
value = -1;
}
}
return value;
}
I was wondering how I could have a program output one of two strings at random.
Hard to explain but this is my example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string age;
cout << "How old are you?" << endl;
cin >> age;
if (age < 0)
{
cout << "Invalid age" << endl;
}
if (0 >= age && age <<= 3)
{
cout << "Oh you're just a baby" << endl;
// OR (random)
cout << "Time to take a nap!" << endl;
}
return 0;
}
I want to program to output either, "Oh, you're just a baby" or "Time to take a nap!" at random whenever the user inputs a number between 0 and 3. Can anybody explain this?
try :
#include <cstdlib>
...
...
...
/* initialize random seed: */
srand(time(NULL));
/* generate secret number: */
int ss = rand() % 2;
if (ss) {
cout << "Oh you're just a baby" << endl;
} else {
cout << "Time to take a nap!" << endl;
}
You can also try this:
take input from user and compare it to random generated value and print output according to it:
#include <iostream>
using namespace std;
int main()
{
int age;
srand(time(NULL));
int a = rand()%3;
cout<<a<<endl; // print the random generated number (between 0 and 3 )
cout << "How old are you?" << endl;
cin >> age;
if (age < 0)
{
cout << "Invalid age" << endl;
}
if(age == a){
cout << "Oh you're just a baby" << endl;
}else{
cout << "Time to take a nap!" << endl;
}
return 0;
}
This uses the STL and only does the random selection from a table, without any user input:
#include <array>
#include <chrono>
#include <cstddef>
#include <iostream>
#include <random>
using std::cout;
using std::endl;
int main(void) {
// The size of the table:
constexpr size_t n = 2;
// A table of insults:
constexpr std::array<const char*, n> insults = {
"Oh, you're just a baby!",
"Time to take a nap."
};
// Boilerplate to initialize a RNG:
const std::default_random_engine::result_type seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
// Generate a random index into the string table:
std::uniform_int_distribution<size_t> distribution(0, n-1);
// A random number from distribution:
const size_t x = distribution(generator);
// Our random string:
const char* const s = insults[x];
cout << s << endl;
return EXIT_SUCCESS;
}
Very new to programming and l can't find any basic explanation online or code that will work well for what l need. I have a fairly long piece of programme (approx 300 lines) it all works. This is the structure to give an idea:
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
//code....
{
//code... etc...
}
}
I want to ask the user to repeat the programme. If enters y, then repeat int main up to the point of asking the same repeat question again. Else to cout<< "e.g. Thank you, goodbye";
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>
//using namespace std; <--- Don't use using namespace std, it pollutes the namespace
void repeat()
{
//... code to repeat
}
int main()
{
//code....
char answer;
while((std::cin >> answer) != 'y')
{
repeat();
}
}
#include <iostream>
#include <conio.h>
using namespace std;
//Class
class DollarToRs {
public:
int Dollar;
int Rs;
int ToRs;
ConversionToRs() {
cout << "Enter the amount of Dollar: ";
cin >> Dollar;
ToRs = Dollar * 154;
cout << "This is the total amount in PKR: " << ToRs <<endl;
}
};
int main()
{
//Dollar Convertion Function
DollarToRs convert;
convert.ConversionToRs();
//For Repeating Program
int repeat;
int exit;
cout << "To repeat program enter 1" <<endl;
cin >> repeat;
while (repeat == 1) {
convert.ConversionToRs();
cout << "To repeat program enter 1" <<endl;
cin >> repeat;
}
exit =0;
if (exit == 0) {
}
getch();
return 0;
}
Here's an example of a simple solution:
int main()
{
for (;;) // "infinite" loop (while (true) is also possible)
{
// stuff to be repeated here
cout << "Repeat? [y/n]" << endl;
char answer;
cin >> answer;
if (answer == 'n')
break; // exit loop
} // else repeat
cout << "Thank you, goodbye" << endl;
}
Here's another one:
int main()
{
bool repeat = true;
while (repeat)
{
// stuff to be repeated here
cout << "Repeat? [y/n]" << endl;
char answer;
cin >> answer;
repeat = answer == 'y';
}
cout << "Thank you, goodbye" << endl;
}
As a side note, don't do this: #include <stdlib.h>. In C++ you should use the c prefixed header file names when using the C headers: #include <cstdlib> and #include <ctime>.