【问题标题】:If statement does not complete code and skips getting user input如果语句未完成代码并跳过获取用户输入
【发布时间】:2020-04-13 14:15:33
【问题描述】:
#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 语句的其余部分。然而,如果语句被跳过并且其余代码运行,则发生的是辅助输入。谁能说出为什么这些 if 语句没有正确执行?

【问题讨论】:

  • char 是单个字符,您可能需要 std::string 代替。
  • 好的,我已将我的字符更改为现在的字符串。在这个例子中我将如何使用字符?可能是一个愚蠢的问题,但出于学习目的,我对答案很感兴趣。

标签: c++ if-statement fstream cin cout


【解决方案1】:

您在密码的第一条和第二条语句中评估相同。在第一个声明中:

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

第二个:

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

都是一样的。在第二个 if 语句中尝试这个:

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

【讨论】:

    【解决方案2】:

    正如其他人所说 你使用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;
    

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

    如果你改变这行

    char game;
    char username;
    char passwordOnline;
    

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

    它会正常工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2022-01-21
      • 2012-03-15
      • 2015-07-11
      相关资源
      最近更新 更多