If语句未完成代码,并跳过获取用户输入的内容

问题描述 投票:0回答:1
#include <iostream>
#include <cstdlib>
#include <crime>
#include <stream>
#include <cmath>
using namespace std;

char game;
char username;
char passwordOnline;
int password = 2427;
int password2 = 2724;
int answer1;
int answers;



int main()
{
cout << "Hello Welcome to PasswordHolder by ItsScrandy \n";
cout << "Please Enter The First Password: \n";
cin >> answer1;
cout << "Please Enter The Second Password \n";
cin >> answer2;

if (answer1 == password && answer2 == password2)
{
    cout << "What Is The Game Called? \n";
    cin >> game;

    cout << "What Is The Username/Email? \n";
    cin >> username;

    cout << "What Is The Password? \n";
    cin >> passwordOnline;
  }
    if (answer1 == password || answer2 == password2)
    {
        cout << "One of the password's you have enterd is incorrect";

    }
    else {
        cout << "Wrong Password";
    }

    //creating a .txt file 
    ofstream pctalk;
    pctalk.open("Login Details.txt", ios::app);

    //actually logging
    pctalk << "Game: " << game << " | " << "Username/Email: " << username << " | " << "Password: " << 
passwordOnline << "\n";
    //closing our file
    pctalk.close();
    return 0;
}

当我运行代码时,在要求用户提供游戏之前,我的程序似乎运行良好。输入后它会自动运行其余的if语句。但是,如果语句被bing跳过并且其余代码运行,那么将发生辅助输入。谁能说出这些if语句执行不当的原因吗?

c++ if-statement fstream cin cout
1个回答
0
投票

您正在对第一和第二条密码进行相同的评估。在firts语句中:

if (answer1 == password && answer2 == password2)

在第二个:

if (answer1 == password || answer2 == password2)

是相同的。尝试第二个if语句使用此方法:

if (answer1 != password || answer2 != password2)

0
投票

正如其他所说您使用char而不是std::string

您的代码中有3个cin

cout << "What Is The Game Called? \n";
cin >> game;

cout << "What Is The Username/Email? \n";
cin >> username;

cout << "What Is The Password? \n";
cin >> passwordOnline;

如果您的游戏名称每个cin超过3个字符,则cin给1 char,因为您只读取了1个字符,而其他字符仍留在cin缓冲区中

如果您更改此行

char game;
char username;
char passwordOnline;

std::string game;
std::string username;
std::string passwordOnline;

它将正常工作

© www.soinside.com 2019 - 2024. All rights reserved.