C++ password program, encountering problems with spaces - string

#include <iostream>
#include <string>
#include <sstream> // don't mind this
#include <ctime> //don't mind this either
using namespace std;
int main() {
const string password = "hello"; //password
char word[100]; //if this were string and I put 2 words in my password it would output "invalid password" twice
do {
cin >> word;
cin.getline(word, 100);
if (word == password) { //if word is equal to password, break and move on past the loop
break;
}
cout << "Password invalid" << endl; //password not equal, it will move on to this and repeat until password is true
} while (true);
cout << "Password valid" << endl;
return 0;
}
I've been new to c++ programming for a couple months now, and I'm watching a very good course right now. In one of the tutorials he makes this password program that is present above. I've played with the program some and noticed that when I input 2 words like "example password" it would output "Invalid password" twice. I assume that is because it recognizes spaces as another input. I've made some changes so that now when I input 2 words or more it only outputs invalid password once. But now I'm facing another problem which I need help on. When I try to input the correct password, it doesn't work. What could be the answer to this mystery? Help would be appreciated and this could help me and others understand this more, and help avoid this problem in the future.

I'm glad that I already solved your problem, but let me elaborate on what I said earlier as it will be helpful for learning.
scanf("%[^\n]%*c", string );
Here the [^\n] is the scanset specifier for the scanf function, it means that the scanf function scans for characters from stdin untill it reaches a newline. This is basically a c function.
The parallel in cpp is getline(stream, char *) function, but almost all c code works in c++ hence you can use it.

Related

How does visual studio read instructions from code?

Hi there StackOverflow community. I’ve faced a certain issue in understanding how visual studio processes the ‘instructions’ given by the code.
the code I’ve written was giving me a problem when i was running it.
It went something like:
whats your guess?
donkey
whats your guess?
donkey
your guess was: donkey
whats your guess?
dog
whats your guess?
dog
your guess was: dog.
It works correctly on alternative tries.
However, if i were to remove ' GetGuess();' on line 38. everything works perfectly fine.
However, it just bothers me that the Getguess on line 38 is nt require because the thought im having right now is that it has to process Getguess first before it processes giving back the guess.
Thank you
code:
#include <iostream>;
#include <string>;
using namespace std;
void PrintIntro();
void play_game();
string GetGuess();
// entry point for out application
int main()
{
PrintIntro();
play_game();
}
//intro game
void PrintIntro()
{
constexpr int WORD_LENGTH = 5;
cout << "welcome to bulls and cows\n";
cout << "can you guess the " << WORD_LENGTH << " letters word?\n";
return ;
}
void play_game()
{
// loop for number of turns asking for guesses
constexpr int number_of_turn = 5;
for (int count = 1; count <= number_of_turn; count++)
{
GetGuess();
string guess = GetGuess();
cout << "your guess was:" << guess << endl;
}
}
//gut guess from player
string GetGuess()
{
// ask for a guess
cout << "whats your guess?\n";
string guess = "";
getline(cin, guess);
return guess;
}
A piece of advice: When you run the code please put breakpoints, especially if you want to know how your code run.
"It works correctly on alternative tries. However, if i were to remove ' GetGuess();' on line 38. everything works perfectly fine. However, it just bothers me that the Getguess on line 38 is nt require because the thought im having right now is that it has to process Getguess first before it processes giving back the guess."
To answer your question, first your must know that, when you call "string guess = GetGuess();" the compiler already retrieve the return value and store it into "guess" (in this case, the function return guess), therefore you don't have to add GetGuess() anymore (this is redundant). Your thinking that the compiler needs to "process Getguess first" is incorrect since "string guess = GetGuess();" is already processing/retrieving the return value.
Also, I think it's a good practice to initialize and declare all functions before int main() but then, it's up to how you organize all your code functions.

I used cin to get a string input as shown below in the code and it works fine. Is it alright?

#include<iostream>
#include<stdio>
using namespace std;
int main()
{ int n;
char s[15];
cin>>n;
cin>>s;
cout<<n*2<<"\n";
cout<<s;
return 0;
}
I tried with gets and fgets function but they don't work just after cin..
I'm kind of confused on what you are asking here, but I have noticed something here that can be fixed.
Yes the code you have compiles and it works. However, it could be improved.
When prompted to input something to your char array, you'll notice that it will not accept whitespaces. So if I input, Jon Smith, the output will only be Jon and the rest of the string input is cut off. To fix this, you will need to make a call the the getline() function.
The documentation of getline() states:
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n'..)
This will allow you to get whitespaces from the input and put the entire input back into a string.
If you add this function call to your code where the second input prompt lies and you were to run the code, you would notice that you will only get prompted once and then the program would finish running before the second prompt appears to be executed. This is because getline() does not ignore leading whitespace characters and it stops reading any further because the cin>> before it is seen as a newline character.
To make getline() work with cin>>, you must use cin.ignore() before the call to getline(). Below is some code that I wrote to make this adjustment:
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string s; //using string allows us to use getline()
cout<<"Enter a number: "; //Let user know they are being prompt for number
cin>>n;
cin.ignore(); //ignore the leading newline
cout<<"Enter a string: "; //let user know being prompt for string
getline (cin,s);
cout<<n*2<<"\n";
cout<<s;
return 0;
}
Again, the code you have works and compiles. I'm not sure if my solution is the answer you are hoping to get but I hope that you are able to find this useful! Cheers!

Error on the first code I wrote on C++. Don't know what's happening

I wrote this code for my class and when i debug it runs but shuts down within seconds i dont know what i'm doing wrong here. I am really new to C++ so.
here is the code:
#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double gallons;
double startmile;
double endmile;
double totalmilestravelled;
cout << "This Program Calculates your vehicle's gas mileage on this trip\n" << endl;
cout << "What is the number of gallons consumed on the trip: ";
cin >> gallons;
cout << "\nWhat was your ending mile?";
cin >> endmile;
cout << "\nWhat was your starting mile?";
cin >> startmile;
totalmilestravelled = endmile-startmile;
double mpg = totalmilestravelled/gallons;
cout << "your gas mileage is: " << mpg << endl;
return 0;
}
and this is the error:
The program '[9848] gasmileage.exe: Native' has exited with code 0 (0x0).
That's not an error. The program exited normally. When you run a program, it executes and exits with an exit code specified by the program. In this case you return 0, so the program exits with code 0. If you want the program to "pause" to allow you to see the result of the program before it closes, add this just before the return statement:
cin.ignore(128, '\n');
cin.get();
The first line discards newlines that were left over in the standard input. Don't worry about this too much until you learn more about the input stream, but you need to do this if you are attempting to read a string after reading numeric input from the user. The second line will prompt the user for some input (push return). You don't care what the input is, and you aren't going to do anything with the input. You just want to force the program to wait for user input so that you can see what's going on before continuing with the program (which in this case the program immediately exit).
Think about programs that say "Press any key." It's the same thing we're doing here. Giving the user a moment to view the output.

how to convert mpf_class to String

Hello and sorry for my basic English. I'm trying to convert from mpf_class to a String. I know there is a function (get_str()) but it show me only digits and its exponent separated. I want to get the whole expression in a string. I tried using ostreamstring and it work but I want to know if there is another way to do that. Let me know if I made myself clear.
Basically what I did was:
std::ostringstream show;
mpf_class result, Afact,Bfact,Cfact;
result=Afact*Bfact/Cfact;
show << result;
ui->lineEdit_5->setText(QString::fromStdString(show.str()));
As you can see, I'm working in a QT project and I need to show the result in a QLineEdit and with ostreamstring it works. I just was wondering if there is a gmp function to do that. thanks
Not sure whether this can help you, but you can actually print an mpf_class object and use I/O manipulators on it as a typical float object.
Here is my code
#include <gmpxx.h>
#include <iostream>
#include <iomanip>
int main(void) {
mpf_class a;
a = 3141592653589793.2;
std::cout << a << std::endl;
// Outputs 3.14159e+15
std::cout << std::uppercase << std::showpos << std::setprecision(3) << a << std::endl;
// Outputs +3.14E+15
}
Then you can use an std::ostringstream object instead of std::cout.
Reference: https://gmplib.org/manual/C_002b_002b-Formatted-Output.html

How to handle strings in VC++?

HI,
Once we accept an input from a keyboard, How can we add that character into a string in VC++?
Can anyone help me with this?
You can use std::string from STL, and the + or += operator.
To do this, #include <string> and use the class std::string.
After that, there are various ways to store the input from the user.
First, you may store the character input directly into the string:
std::string myStr;
std::cin >> myStr;
Second, you can append the input to an existing string:
std::string myStr;
myOtherStr += myStr;
#include <iostream>
#include <string>
int main(int argc, char**argv)
{
std::string s;
std::cin >> s;
s += " ok";
std::cout << s;
return 0;
}
Try the following:
std::string inputStr;
std::cin >> inputStr;
This code will accept a string typed on the keyboard and store it into inputStr.
My guess is that you're in the process of learning C++. If so, my suggestion is to continue reading your C++ book. Keyboard input will surely be addressed in some upcoming chapter or the other.
There are several ways to go about, depending of what you exactly need. Check the C++ I/O tutorial at this site: www.cplusplus.com

Resources