簡體   English   中英

如何修正while語句以顯示正確的提示?

[英]How to fix a while statement to display correct cout?

我怎樣才能獲得cout在我的身上while聲明在它之外打印嗎? 原因是因為當我嘗試在cout << password;行中加上句子時cout << password; 它會弄亂我的password

例如,如果我寫cout << "this is your new password " << password; ,它將在句子末尾顯示一個數字。

如果有人可以給我一些幫助,我將不勝感激。

下面是我的程序:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    //Introduction on how the password generator works
    cout << "This program will help you generate a passowrd."
        << "\nPlease enter your password in character or number followed by <ENTER> key."
        << "\n*Please note that character must be in lower case letters or digits.*" << endl
        << "Input your Password: ";

    //char to hold user password
    char password;
    //user input for password
    cin.get(password);
    //while loop for password until it hit a blank
    while (password !='\n')
    {
    //if and else if statement for password
        if (password == 'a' || password == 'b' || password == 'c' || password == '1')
        {
            password = '1';

        }

        else if (password == 'd' || password == 'e' || password == 'f' || password == '2')
        {
            password = '2';
        }

        else if (password == 'g' || password == 'h' || password == 'i' || password == '3')
        {
            password = '3';
        }

        else if (password == 'j' || password == 'k' || password == 'l' || password == '4')
        {
            password = '4';
        }

        else if (password == 'm' || password == 'n' || password == 'l' || password == '5')
        {
            password = '5';
        }

        else if (password == 'p' || password == 'q' || password == 'r' || password == '6')
        {
            password = '6';
        }

        else if (password == 's' || password == 't' || password == 'u' || password == '7')
        {
            password = '7';
        }

        else if (password == 'v' || password == 'w' || password == 'x' || password == '8')
        {
            password = '8';
        }

        else if (password == 'y' || password == 'z' || password == '9')
        {
            password = '9';
        }
        else
        {
            password = '?';
        }

        // cout to print new password
        cout <<password;
        //cin.get to restart loop
        cin.get(password);

    }       

    return 0;
}

您可以使用“ endl”在新行中顯示密碼,這樣就不會弄亂密碼:

cout << "this is your new password " <<endl<< password;

你不能得到cout里面while循環事后打印。 如果它在while循環中,它將在每個循環中執行(直到被if左右包圍)。

因此,您有兩種選擇:

  1. 在進入while循環之前,打印您的句子,如下所示:

     cout << "Your new password..."; while(password!='\\n'){ ... cout << password; } 
  2. 將您的“密碼”(不是真正的單詞,而是單個字符)存儲在這樣的字符串中:

     std::string str = ""; while(password!='\\n'){ ... str += password; } cout << "Your new password..." << str; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM