In this code you will see it asks for a password. Please note that there is no real password system setup. I am new to c++ and I literally just learned about strings. I understand them but I am not getting good results. It is operating backwords? I do not understand string completely so I do not understand what is happening. I tried googling it but I couldn't find anything.
When I flip username with password it works just fine. So why is it running backwords?
#include <iostream>
#include <string>
std::string password()
{
std::cout << "Please enter your password. : ";
std::string password;
std::getline(std::cin, password);
return password;
}
std::string username()
{
std::cout << "Please enter your username. : ";
std::string username;
std::getline(std::cin, username);
return username;
}
int main()
{
std::cout << "Welcome to the test login! Please enter your username and password to enter. \n \n \n";
std::cout << username() << password() << "\n \n \n";
int noEnd{ 0 };
std::cin >> noEnd;
return 0;
}
Notice if I swap password with username it works.
std::cout << "Welcome to the test login! Please enter your username and password to enter. \n \n \n";
std::cout << password() << username() << "\n \n \n";
But this does not make sense to me. I am knew to c++ and just learned the basics of strings. Theoretically if I have the code like,
std::cout << "Welcome to the test login! Please enter your username and password to enter. \n \n \n";
std::cout << username() << password() << "\n \n \n";
username() should go first but, password() does instead?
Sorry I am knew please don't use like weird functions and things because I will probably not understand them . . . Yet.
Your compiler is evaluating std::cout << password() << username() << "\n \n \n" from right to left.
According to ccpreference
Order of evaluation of the operands of almost all C++ operators
(including the order of evaluation of function arguments in a
function-call expression and the order of evaluation of the
subexpressions within any expression) is unspecified. The compiler can
evaluate operands in any order, and may choose another order when the
same expression is evaluated again.
The best option is to write code in a way that does not depend on the order it is evaluated.
std::string u = username();
std::string p = password();
std::cout << u << p << "\n \n \n";
Related
#include<iostream>
using namespace std;
int main()
{
int num1,num2,result;
cout << "enter num 1"<<endl;
cin >> num1;
cout << "enter num 2"<<endl;
cin >> num2;
result = num1 + num2;
cout << num1 <<"+" << num2 << " = "<< result;
return 0
}
this is the code I am unable to enter in output for adding the numbers
I wrote c++ code of adding two nums when output is given to enter 1st no then I am unable to write the no how can I write that output
The last sentence your code :"return 0",didn't write ";".
string fullname, empid;
double hours, pay, fedrate, staterate, medicare = 1.5, socialtax = 6.2, overtime, overtimepay;
int option;
cout.precision(2);
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout << "Enter Employee's Full Name: " << endl;
cin >> fullname;
cout << "Enter Employee's ID: " << endl;
cin >> empid;
cout << "Enter Hours Worked: " << endl;
cin >> hours;
hours = fabs(hours);
cout << "Enter Pay Rate: " << endl;
cin >> pay;
pay = fabs(pay);
cout << "Enter Fed Tax Rate: " << endl;
cin >> fedrate;
fedrate = fabs(fedrate);
cout << "Enter State Tax Rate: " << endl;
cin >> staterate;
staterate = fabs(staterate);
After inputing a name for fullname it skips the employee id and goes straight into asking for hours worked. Do I have to use getline to fix that or did i do something wrong?
Yes. See here:
http://www.cplusplus.com/doc/tutorial/basic_io/
"However, cin extraction always considers spaces (whitespaces, tabs, new-line...) as terminating the value being extracted, and thus extracting a string means to always extract a single word, not a phrase or an entire sentence.
To get an entire line from cin, there exists a function, called getline, that takes the stream (cin) as first argument, and the string variable as second. For example:"
I have a user input of this kind:
A+B*C;
A*(B+c);
C+F.
Now I want to parse this input and get all sub-strings until the semi-colons and stop scanning when I run into a period symbol.
What is the simplest way to achieve this ?
Also, I have freedom to take input from a file or from the console. Which one would be the easiest to implement ?
I have a method to read from the console as such :
cout << "Enter input: " << endl;
char delimiter = '.';
string inputStr;
getline(cin,inputStr,delimiter);
cout << inputStr;
But if I enter the above mentioned sample input I read only until before period symbol is recieved. So while finding sub strings, what stopping criteria or flag should I take ?
TIA
EDIT:1
Code so far:
#include <string>
#include <iostream>
using namespace std;
int main()
{
cout << "Enter input: " << endl;
char delimiter = '.';
string inputStr;
getline(cin,inputStr,delimiter);
cout << inputStr;
string deli = ';';
size_t pos = 0;
string token;
while ((pos = inputStr.find(deli)) != std::string::npos) {
token = inputStr.substr(0, pos);
std::cout << token << std::endl;
inputStr.erase(0, pos + deli.length());
}
std::cout << inputStr << std::endl;
};
ANSWER:
I was wrongly initializing the string deli. I had to do this :
string deli = ";". Instead of single-quotes, I had to use double-quotes, because it a string and not a character! Final working solution here: https://repl.it/EPyC/2
Use getline with delim ; for all lines. Check for dot(.) for last line.
string line;
while(getline(cin, line, ';')){
if(line.back() == '.')
line.pop_back();
cout << line <<endl;
}
I have a very strange problem. Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string user_name;
cout << "what is your name?" << endl;
getline(cin, user_name, '\n');
cout << "hello, " << user_name << ", how are you today?" << endl;
}
This code doesn't end when I push Enter at all; therefore there is no way to complete the input. The output will stop like this and wait:
what is your name?
However if I change '\n' to 'p' or whatever char, it will finish the input when the specific char is input. For instance:
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string user_name;
cout << "what is your name?" << endl;
getline(cin, user_name, '\p');
cout << "hello, " << user_name << ", how are you today?" << endl;
}
Screen:
what is your name?
hello, Frank, how are you today?
RUN SUCCESSFUL (total time: 2s)
PS:
I am using NetBeans IDE 8.0 and Windows 8 Pro x64
New Line character depends on the operating system.
Reminder - \r\n or \n\r?
I would leave out the third parameter of the getline call all together. This will use getline's default behavior and terminate the read on the enter key.
EDIT: After reading you are still having problems, I decided to run some tests on your code.
First, to confirm that the default behavior works without specifying the third parameter to the getline method.
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
while(true){
string user_name;
cout << "what is your name?" << endl;
getline(cin, user_name);
cout << "hello, " << user_name << ", how are you today?" << endl;
}
}
The output:
what is your name?
WhiteboardDev
hello, WhiteboardDev, how are you today?
what is your name?
WhiteboardDev
hello, WhiteboardDev, how are you today?
what is your name?
WhiteboardDev
hello, WhiteboardDev, how are you today?
what is your name?
Second, to test manually specifying the escape sequence '\n' i did this:
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
while(true){
string user_name;
cout << "what is your name?" << endl;
getline(cin, user_name, '\n');
cout << "hello, " << user_name << ", how are you today?" << endl;
}
}
And the output:
what is your name?
WhiteboardDev
hello, WhiteboardDev, how are you today?
what is your name?
WhiteBoardDev
hello, WhiteBoardDev, how are you today?
what is your name?
WhiteboardDev
hello, WhiteboardDev, how are you today?
what is your name?
compiled on g++ w/osx so i didnt bother testing the '\r\n' case. This brings up a good point about cross platform compatibility. If you want your code to work in multiple environments try to not specify anything platform specific in your code (aka the EOL sequence) and leave out that third parameter entirely.
Now I have solved my question with the help of WhiteboardDev. In my coding environment, I should use '\r' and during the input I need push Enter and Space, two keys in order to complete the it.
O.F community! I'm very new to c++ and I decided to create my own game.
My issue is that at one point in the game the player is asked to answer 3 things:
-Gender
-Age
-Setting
void assessment()
{
cout << "Now that the characteristics have been selected. Let's review what they are:\n\n";
cout << "Press any key to continue\n\n";
cin >> anykey;
cout << "You are a " << ageNumber << " year old " << gender; //incomplete - needs //<< setting;
}
The issue is with gender not being displayed. It can cout << ageNumber fine. But when the game is played and this part is reached this is what it says:
Now that the characteristics have been selected. Let's review what they are:
Press any key to continue
1
You are a 16(that is what I put for ageNumber earlier on) year old . <- Notice how "old" and "." have a space? As if the string gender is read as a blank.
EDIT: It is supposed to say:
You are a 16 year old male/female/it.
This is the part that determines the gender.
void fate()
{
cout << "Before we begin, a few characteristics must be selected\n\n";
cout << "Gender?\n\n";
cout << "1. Male\n";
cout << "2. Female\n";
cout << "3. Other\n\n";
cin >> genderNumber;
cout << "Now your next characteristic...Press any key to continue\n\n";
cin >> anykey;
cout << "What is your age? (Must be younger than 50 to play)\n\n";
cin >> ageNumber;
setting2();
if (genderNumber == 1)
{
string gender = "male";
}
else if (genderNumber == 2)
{
string gender = "female";
}
else if (genderNumber == 3)
{
string gender = "'it'";
}
else
{
"invalid input\n\n\n\n\n\n";
fate();
}
===========================================================================================
This is the full code:
#include <iostream>
#include <string>
using namespace std;
void rules();
void controls();
void start();
void fate();
void assessment();
void setting2();
int fateNumber;
int anykey;
int ageNumber;
int settingNumber;
int genderNumber;
string gender;
string setting;
int main(int argc, char** argv)
{
cout << "===W E L C O M E T O C H O O S E Y O U R F A T E=== \n\n";
cout << "Press any key to continue\n";
cin >> anykey;
start();
}
void controls()
{
cout << "Throughout this game will you be making choices, each choice will have a corresponding number next to it. Press the letter to the corresponding choice you want to make. Press any key to continue\n";
cin >> anykey;
cout << "Here is an example...you are a cat, you can either\n\n";
cout << "1. Meow\n\n";
cout << "2. Hiss\n";
cout << "Press any key to continue\n";
cin >> anykey;
cout << "If I wanted to Hiss I would press the 2 key\n\n";
cout << "Press any key to continue on to the rules\n\n";
cin >> anykey;
rules();
}
void rules()
{
cout << "#1 You will be given a set number of choices. Press any key to continue\n\n";
cin >> anykey;
cout << "#2: There are 2 factors to this game. Press any key to continue\n\n";
cin >> anykey;
cout << "#3: The first factor is that either you live or you die. Press any key to continue\n\n";
cin >> anykey;
cout << "#4: The second factor is that if you live, your character will be judged based on events you've made. You can still live, but you might have a good or bad effect on the people around you. Press any key to continue\n\n";
cin >> anykey;
cout << "Let's play shall we?";
}
void start()
{
cout << "You shall begin a journey that'll decide either you make it or you don't. Press any key to continue\n\n";
cin >> fateNumber;
cout << "But before we start...The game needs to be explained.\n\n\n\n";
cout << "Controls(1 key)---------------------------Rules(2 key)---------------Skip(3 key) \n\n";
cin >> fateNumber;
if (fateNumber == 1)
{
controls();
}
else if (fateNumber == 2)
{
rules();
}
else if (fateNumber == 3)
{
fate();
}
else
{
cout << "invalid key\n\n\n\n\n\n\n";
start();
}
}
void fate()
{
cout << "Before we begin, a few characteristics must be selected\n\n";
cout << "Gender?\n\n";
cout << "1. Male\n";
cout << "2. Female\n";
cout << "3. Other\n\n";
cin >> genderNumber;
cout << "Now your next characteristic...Press any key to continue\n\n";
cin >> anykey;
cout << "What is your age? (Must be younger than 50 to play)\n\n";
cin >> ageNumber;
setting2();
if (genderNumber == 1)
{
string gender = "male";
}
else if (genderNumber == 2)
{
string gender = "female";
}
else if (genderNumber == 3)
{
string gender = "'it'";
}
else
{
"invalid input\n\n\n\n\n\n";
fate();
}
if (ageNumber >= 50 && ageNumber < 100)
{
cout << "Didn't you read the age rating dumbass? Younger than 50...\n\n";
}
else if (ageNumber < 50 && ageNumber > 22)
{
setting2();
}
else if (ageNumber <= 22 && ageNumber >= 16)
{
setting2();
}
else if (ageNumber < 16 && ageNumber >= 0)
{
setting2();
}
else if (ageNumber >= 100)
{
cout << "More than a century old and you expect me to believe you got this far? Bullshit.";
}
else
{
cout << "Error - Invalid number\n\n\n\n\n\n";
cout << "what is your age again?\n\n";
cin >> ageNumber;
}
}
void assessment()
{
cout << "Now that the characteristics have been selected. Let's review what they are:\n\n";
cout << "Press any key to continue\n\n";
cin >> anykey;
cout << "You are a " << ageNumber << " year old " << gender << ". You are " << setting << endl << endl;
if (settingNumber == 1)
{
string setting = "home";
}
else if (settingNumber == 2)
{
string setting = "jail";
}
}
void setting2()
{
cout << "Alright and lastly pick your setting\n\n";
cout << "1. Home sweet home\n";
cout << "2. Vacation \n";
cout << "3. Jail\n\n";
cin >> settingNumber;
assessment();
}
=======================================================================================
Any help is appreciated ^^ Code on!
Output (thru ofstream-s like cout) is buffered in C++. You want
cout << flush;
or
cout << endl;
to ask the buffer to be flushed (endl manipulator also emits a new line but flush does not).
So code:
cout << "You are a " << ageNumber << " year old " << gender << flush;
or
cout << "You are a " << ageNumber << " year old " << gender << endl;
Also, your gender should be declared at a wider scope:
if (genderNumber == 1) {
string gender = "male";
}
should become (to refer to the global gender)
if (genderNumber == 1) {
gender = "male";
}
BTW, if you enabled all warnings with your compiler (e.g. compile with g++ -g -Wall -Wextra, if using GCC, e.g. on Linux) you should have been warned. And of course, you should use the debugger (e.g. gdb, at least on Linux) and step into your code with it.