To begin with I have decided to post my code here so everyone can understand the issues I have with the code and will be able to assist me better.
main.cpp
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include "validate.h"
#include "main.h"
using namespace std;
int main() {
name = getName();
score = quiz();
cout << "\n\n";
system("pause");
return (0);
}
string getName() {
cout << "Enter your name: ";
getline(cin, name);
val.set_item(name);
valid = val.vName();
if (valid) return name;
else {
cout << "Invalid name!\n\n";
getName();
}
}
int quiz() {
for (int loop = 0; loop <= 10; loop++) {
rand1 = rand() % 20 + 1;
rand2 = rand() % 20 + 1;
randop = rand() % 3;
op = operators[randop];
if (op == '*') ans = rand1 * rand2;
else if (op = '+') ans = rand1 + rand2;
else ans = rand1 - rand2;
cout << "What is " << rand1 << op << rand2 << " ? ";
getline(cin, input);
val.set_item(input);
valid = val.vInput();
if (valid) {
istringstream(input) >> inputint;
if (ans == inputint) {
cout << "Correct!\n\n";
score++;
}
else cout << "Incorrect!\n\n";
}
else cout << "Incorrect!\n\n";
}
return score;
}
validate.h
#ifndef validate_h
#define validate_h
using namespace std;
class validate {
string item;
int len;
bool check;
public:
void set_item(string x);
bool vInput() {
len = item.size();
for (int loop = 0; loop < len; loop++) {
if (item[loop] == '-' && loop == 0) continue;
check = isalnum(item[loop]);
if (check) continue;
else return false;
}
return true;
}
bool vName() {
len = item.size();
for (int loop = 0; loop < len; loop++) {
check = isalpha(item[loop]);
if (check) continue;
else return false;
}
return true;
}
};
void validate::set_item(string x) {
item = x;
}
#endif
main.h
#ifndef main_h
#define main_h
string name;
string input;
string getName();
validate val;
bool valid;
int quiz();
int score;
int rand1;
int rand2;
int randop;
int ans;
int inputint;
const char operators[3] = { '-', '+', '*' };
char op;
#endif
Ok so my code compiles fine and goes through everything perfectly. It asks the name, it knows when it is invalid but here comes my first issue. When you enter an incorrect name it again prompts you to enter it. But it crashes when you enter it the second time. Here is a screenshot example.
crash issue
The program also does not generate random numbers. Its the same every single run. Here is a screenshot of that.
duplicating numbers
Any assistance with these issues would be greatly appreciated.
Also for the random issue. I looked up on the other questions and when I tried the fix "srand(time(NULL));" it tells me that srand is ambiguous.
In regards to your application crashing when you call getName(), try flushing the cin buffer using:
cin.ignore();
or
cin.clear();
to clear the buffer state. I had a similar issue a while back which I believe that was the solution to. In regards to your random number, you havent initialized a random seed. Initialize a random seed prior to generating random numbers using:
srand (time(NULL));
Hope this helps.
EDIT:
Just saw your comment above. Try using the following instead for your random number seed:
srand(time(0));
Make sure you do #include <ctime> at the head of file for this solution.
Related
I am setting up a sign up, and login program, but it never allows to login.
At the time of execution, it displays entering two characters while the user types only one, and also at the time of login the password never matches.
Any solutions for goto.
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int i, t = 3;
struct dateob {
int day;
int month;
int year;
};
struct userdetails {
char name[50];
dateob dob;
char country[100];
char residential_address[100];
char office_address[100];
char citizen_proof[100];
long phoneno;
char gender[10];
long money;
char username[100];
char password[100];
};
userdetails ud[3];
char u[100], u1[100];
void Entering(char a, int n)
{
if (a == 'S')
{
cout << "Username ";
cin.ignore();
cin.getline(ud[n].username, 100);
string user = ud[n].username;
cout << "Password ";
for (i = 0; i < 100; i++)
{
ud[n].password[i] = _getch();
if (ud[n].password[i] == 13)
break;
cout << "*";
}
cout << "\n"
<< "User Created\n";
goto login;
}
else if (a == 'L')
{
login:
char username[100], password[100];
cout << "Welcome To Login";
for (int j = 0; j <= 3; j++)
{
cout << "Username ";
cin.ignore();
cin.getline(username, 100);
cout << "Password ";
for (i = 0; i < 100; i++)
{
password[i] = _getch();
if (password[i] == 13)
break;
cout << "*";
}
if (strcmp(username, ud[n].username) == 0 && strcmp(password, ud[n].password) == 0)
{
cout << "You can Enter :)";
break;
}
else
{
cout << "\nSomething went wrong! \n";
cout << "You Left with" << t-- << "Try \n";
}
}
if (t == 0)
cout << "You are Suspicious";
}
}
int main()
{
char a, b, c;
int d;
for (int n = 0; n < 3; n++)
{
cout << "Do you want to enter users :Y/N ";
cin >> b;
if (b == 'Y')
{
cout << "Sign Up : S \n"
<< "Login : L \n";
cin >> a;
Entering(a, n);
}
else
break;
}
return 0;
}
I entered only 2 characters from keyboard but it displays 4 characters.You can see screenshot of result here
I expected that it takes the password, and store it, and then can be used as an reference for Login.
Welcome to SO, Mrigank.
There are several things wrong with this code, I'd like to help you with some pointers if that's okay. Lots of these things are already in the comments.
First, instead of goto, which has lots of problems, use a loop:
bool loginSuccessful = false;
while (!loginSuccessful) {
// Do the login stuff here
}
Second, the phone number really should be a string (looking like you'd probably want to use char[15] or something) in your struct at the top. the double type can be volatile and messy and should really only be used for math and such.
Third, and to answer your question, most terminals in most operating systems echo characters to the console as they're being input into standard in (cin). Differnt OSes let you turn this off in different ways. To quote this post:
In Windows, you can turn off echo for any standard input function with SetConsoleMode().
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main()
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
string s;
getline(cin, s);
cout << s << endl;
return 0;
}//main
In *nix you can use the "termios" interface to disable echo.
#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>
using namespace std;
int main()
{
termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
string s;
getline(cin, s);
cout << s << endl;
return 0;
}//main
You can probably also get a lot of ideas for how to solve this in different ways if the above doesn't work by consulting this SO question.
Finally, your cin calls should probably be completely changed. I have never used ignore() before in this context and it looks odd to me, I don't think it will help you. You are getting up to 100 characters per line (getline(..., 100)) but you should
only be getting 99 characters, so as to leave one character for the null terminator. (This is a byte with a value of 0 that says "the string is terminated, or done".)
Rather than doing a getline, you may just use the >> operator on cin, or better yet, have a look at how the people in the SO answer above and in the forum post are getting input.
Hope this helps.
I was writing a code for a counter. If I give 'a' as input, it should +1 the counter and show it on the screen. But when I do it, it shows 1 on the screen and the program ends. I want it to run until and unless i give some other character as input. What's the mistake I am making?
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
return 0;
}
The issue is when you are entering your 'a', you are probably hitting Enter as well, which is interpreted as another char. That second char is definitely not a, so your program breaks. This can be verified by just outputting what you read:
for (;;) {
std::cout << '?';
char t = std::cin.get();
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
Which, when run, prints:
?a
97 // this is 'a'
?10 // this is '\n', note the additional ?
done
The simplest fix would be to use the input stream operator on cin, which would discard whitespace in the input (whereas get() does not):
char t;
for (;;) {
std::cout << '?';
std::cin >> t;
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
Which, when run, produces:
?a
97
?b
98
done
which is what you'd intended.
Try this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
// else
// break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
Your else break; is the reason why you're closing after any interation. Basically after any iteration, it will break because due to any non-a input. However, running the code above, you will see the counter increment at every a input given and it will not break.
This will give you the basic operation you're looking for which is increment the counter based on input a, otherwise do nothing.
Edit: The above code will buffer your input and read it all, so if you have 5 a's like the following aaaaa, it will read it and output 5 for the counter.
If you want to break out of the loop, i suggest this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
cin >> t;
// t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
I tested it and it works. Seems to be with how cin.get() reads the buffered input from the console (i think). Not too sure on the specifics, but cin >> t does the trick.
Edit 2: Did some reading and i think cin.get() will consume the next character after your input, but in this case it is a newspace \n, which is why it will always break in your original code.
I am instructed that I have to reject any decimal and I need to re enter the number again.I tried this code but still it just goes to the whole process before acknowledging the error. Try the program and judge me :D here's my code:
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<limits>
using namespace std;
int getInt()
{
int m=0;
while (!(cin >> m))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Please input a proper 'whole' number: " ;
}
return (m);
}
int main()
{
double x;
int q,w,e,choice;
cout<<"Welcome! This program will sort out the integers you will input!\nPlease input number of integers: ";
cin>>q;
cout<<endl<<endl;
int* inc= new int[q];
int* dec= new int[q];
for(int p=1;p<=q;++p)
{
w=p;
e=p;
cout<<"Input integer number "<<p<<": ";
x =getInt();
while(e>0 && inc[e-1]>x)
{
inc[e]=inc[e-1];
e--;
}
while(w>0 && dec[w-1]<x)
{
dec[w]=dec[w-1];
w--;
}
inc[e]=x;
dec[w]=x;
}
cout<<endl;
cout<<"What order do you prefer? Input 1 for increasing and 2 if decreasing.\nChoice: ";
cin>>choice;
while(choice<1 || choice>2)
{
cout<<"Please input a correct choice! Try again!\nChoice: ";
cin>>choice;
}
if(choice==1)
{
for(int i=0;i<q;++i)
cout<<inc[i]<<"\t";
cout<<endl;
}
else
{
for(int i=1;i<=q;++i)
cout<<dec[i]<<"\t";
cout<<endl;
}
system("PAUSE");
}
hoping for your help :)
You can try using modulo.
Just an idea, hope it helps.
bool flag = false;
While (flag == false){
cin>>number;
if ((number % 1) != 0){
flag = false;
}
else{
flag = true;
}
cin.clear();
}
Try making a copy of the number you want to test and casting it to an int and then back to a double, and then check for equality. If they are equal, you have an int, if they are not, you have a decimal:
#include <iostream>
using namespace std;
int main()
{
double a = 5;
double c = 5.5;
double b = a;
bool test1 = (double)((int)b) == a; //true!
b = c;
bool test2 = (double)((int)b) == c; //false!
cout << test1 << endl;
cout << test2 << endl;
return 0;
}
Wrote this answer a long time ago, it is very hacky and will not work on all inputs. Use std::stoi and check if it throws as the comment suggests instead.
I am trying to get the following code to work:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <cmath>
using namespace std;
bool prime_test(int num);
void stringRotation(string& str);
int main()
{
vector<string> primes;
ifstream infile("PRIMES1T.txt");
// checks to see if there was any problems opening the .txt
if (infile.is_open()) {
string line = "";
while(getline(infile,line)) {
primes.push_back(line);
}
// rotates our string and tests if the number is still prime
vector<string> primes2;
for (int i = 0; i < primes.size(); i++) {
string str = primes[i];
for (int j = 0; j < str.length(); j++) {
stringRotation(str);
int value = atoi(str.c_str());
if (prime_test(value) == false) {
break;
}
if (j == str.length()-1) {
if (prime_test(value) == true) {
primes2.push_back(primes[i]);
}
}
}
}
cout << "There are " << primes2.size() << " primes that work.";
cout << endl;
}
else {
cout << "File failed to open." << endl;
}
return 0;
}
// tests to see if num is a prime number
bool prime_test(int num) {
if (num == 1) {
return false;
}
// Finds first integer value larger than the sqrt of num
// since that is all we really need.
double dnum = num;
double sqrt_dnum = sqrt(dnum);
int counter = ceil(sqrt_dnum);
for (int i = 2; i < counter; i++) {
if (num == 2) {
break;
}
if (num%i == 0) {
return false;
}
}
return true;
}
// rotates a string
void stringRotation(string& str) {
int len = str.length();
// converts a char variable into a string variable
stringstream ss;
string ch;
char c = str.at(0);
ss << c;
ss >> ch;
str = str.substr(1,str.length());
str = str.append(ch);
cout << str << endl;
}
What it does is it takes a prime number say 999983, cuts off the first digit 9, and then adds it to the end of the rest of the number so that it spits out the new number 999839. It then tests whether or not this new number is prime or not and repeats the process until the original number is returned. If the number is prime every time we do this process, then we add that number to the vector primes2.
The problem I have is that the stringRotation function does not work properly for some reason. I have tested it by trying to outputting the string before adding the digit that was removed and outputting the string after adding the digit. It does not concatenate properly. It will cut off the first digit in 999983 so that we have str = '99983' and ch = '9' but then when I do str.append(ch), it still gives me 99983. I have also tried variations like str = str.append(ch) and str = str + ch.
I have tried copying just the function over to a different .cpp file to compile only adding a declaration for str by setting str to "999983" and it works fine.
EDIT
I changed stringRotation to:
void stringRotation(string& str) {
int len = str.length();
char ch = str.at(0);
cout << ch << endl;
str = str.substr(1,str.length());
str.append(1,ch);
cout << str << endl;
}
but the problem still persists. I have also tried string.push_back(ch) with no luck.
In your programmer career, you will need to always make sure that your input is handled well. If you are loading data from a file which is not guaranteed to have a specific content scheme, you will always need to make sure that you prepare your data before parsing. In this particular case you need to make sure that your "numbers" are indeed numbers and execute your stringRotation on values which are guaranteed to be numbers.
I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed.
For example: 17 becomes 71. 123 becomes 321.
This is the program:
#include <iostream>
#include <string> //for later use.
using namespace std;
int rev(int x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
return r;
}
int main()
{
int nr;
cout << "Give a number: ";
cin >> nr;
rev(nr);
cout << nr;
return 0;
}
The final result of the program: prints the same number, function has no effect. What am I doing wrong? I tried several solutions but to no avail.
You need to change rev(nr); to nr = rev(nr);
or alternately change your function to:
void rev(int& x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
x = r;
}
You're doing it right, but you're not grabbing your return value (the reversed value).
To solve this, just assign or print the return value:
cout << rev(nr);
or
nr = rev(nr);
cout << nr;
While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string:
std::string input;
std::cin >> input;
std::cout << std::string(input.rbegin(), input.rend());
You're not actually using the value that rev returns. You're just using the value nr which you pass to rev, and since you don't pass by reference, rev isn't being affected locally.
What you want to say is:
int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result;
return 0;
There is a std::reverse function in the STL, which works with collections.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
long int i = 0;
do {
std::cout << "Gimme a number: " << std::endl;
} while (not (std::cin >> i)); // make sure it *is* a number
std::string display = std::to_string(i); // C++11
std::reverse(display.begin(), display.end());
std::cout << display << "\n";
}