I'm trying to make my code work, actually it works but not that well. The code stops after 'enter' appeared. I want to make my code work until the end of file input from user.
#include<iostream>
using namespace std;
int main(){
char input[2000];
cin.getline(input, sizeof(input));
int lol = strlen(input);
int boing = 0;
for (int p = 0; p < lol; p++)
{
if (input[p] == '\"')
{
boing++;
if (boing % 2 == 1)
{
cout << '\`'<<'\`';
}
if (boing % 2 == 0)
{
cout << '\''<<'\'';
}
}
else
cout << input[p];
}
system("pause");
}
if we enter input these words
Is branched in ""my up strictly "remember. "
Songs but chief has ham widow downs. Genius or so up vanity cannot.
'''```Large do tried goi"'''ng" about water defer by. "Silent" son man she wished mother.
Distrusts allowance do knowledge eagerness assurance additions to.
We """"diminution preference "thoroughly if. "Joy deal pain ';`392view" much her time. Led young gay would now state."
my output become
Is branched in ''my up strictlyremember. ''
but it should be
Is branched in ''my up strictlyremember. '' Songs but chief has
ham widow downs. Genius or so up vanity cannot. '''```Large do tried
goi'''ng'' about water defer by.Silent'' son man she wished
mother. Distrusts allowance do knowledge eagerness assurance
additions to. We ''''diminution preference thoroughly if. ''Joy
deal pain ';`392view much her time. Led young gay would now state.''
getline will take input until the "enter" button is pressed.
Your code runs fine on my machine.
Just add string.h header file like this:
#include<string.h>
This is for the strlen function.
for this code you you need to two more header file
#include <string.h>
#include <stdlib.h>
your full code will be
#include<iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main()
{
char input[2000];
cin.getline(input, sizeof(input));
int lol = strlen(input);
int boing = 0;
for (int p = 0; p < lol; p++)
{
if (input[p] == '\"')
{
boing++;
if (boing % 2 == 1)
{
cout << '\`'<<'\`';
}
if (boing % 2 == 0)
{
cout << '\''<<'\'';
}
}
else
cout << input[p];
}
cout<<endl; //this line is for making ur code look nice
system("pause");
}
but i personally suggest you to use c++ string class for string handling
it easy and very useful
using string class your code will be
#include<iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string input;
getline(cin,input);
int lol = input.size();
int boing = 0;
for (int p = 0; p < lol; p++)
{
if (input[p] == '\"')
{
boing++;
if (boing % 2 == 1)
{
cout << '\`'<<'\`';
}
if (boing % 2 == 0)
{
cout << '\''<<'\'';
}
}
else
cout << input[p];
}
cout<<endl;
system("pause");
return 0;
}
Happy Coding
You need to wrap your getline in some form of loop. Right now you are getting 1 line, then manipulating input then exiting. Right now you are pulling it in from the user so you need to look for a terminator.
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.
My assignments requires me to keep accepting input from the user and output whether or not it is a palindrome until the word DONE is inputed.
Also, words like Bob must have an output of true because we must disregard case (upper/lower.)
This is my first time using C++.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string wordInput;
while (wordInput != "DONE")
{
cout << "Please enter a word: ";
cin >> wordInput;
int wordLength = wordInput.length();
int wordHalf = (wordLength / 2);
bool flag = false;
for (int i = 0; i <wordHalf; i++)
{
if (tolower((wordInput[i]) == tolower(wordInput[wordLength-1-i])))
{
flag = true;
}
else
{
flag = false;
break;
}
}
if (flag == true)
{
cout << "true"<<endl;
}
else
{
cout << "false"<<endl;
}
}
return 0;
}
It might have something to do with 'wordInput' being declared twice, once right before the while loop and once within it. It is mixing up what the while loops condition is looking at.
Your issue with words not being correctly identified comes from this line:
if(tolower((wordInput[i]) == tolower(wordInput[wordLength-1-i])))
If you look carefully, you set the parentheses incorrectly. Try this instead:
if(tolower(wordInput[i]) == tolower(wordInput[wordLength-1-i]))
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.
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.
Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
return 0;
}