簡體   English   中英

c++ 初學者,string.replace,代碼編譯但終止 - 你如何用另一個字符替換數字?

[英]c++ beginner, string.replace, code compiles but terminates - how do you replace numbers with another character?

在我的代碼中,我試圖提示用戶輸入他們的姓名、社會保險號、用戶 ID 和密碼,同時以"xxx-xx-xxx"格式輸出社會保險號,基本上將所有數字替換為x ,並且x的密碼中的字符也是如此。

雖然,我嚴重卡在最初的社會保障部分,因為當我測試它時,代碼編譯了,但它終止了。 我認為我的問題是我對循環感到困擾。 我應該為這個循環制作一個 function,還是這完全錯誤? 有人可以向我解釋string::replace() function 以及string::insert() function 嗎?

我明白了它的要點,但把它付諸實踐是我覺得我失敗得很慘的地方!

這是我到目前為止所擁有的:

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

string topSecret(string);//prototype for topSecret function after main

int main()
{
    //Top Secret Input
    string name, social, userName, password;
    cout << "Enter your first name, Social Security number (digits only), userID (no spaces within ID), and password (no spaces within password) - with a space between each entry: ";
    cin >> name >> social >> userName >> password;
    cout << "Name: " << name << endl;
    cout << "SSN: " << social.replace(0,social.length(), "X");
    cout << "SSN: " << social.insert(2,"-") << endl;
    cout << "UserID: " << userName << endl;
    cout << "Password: " << topSecret(password) << endl;

    return 0;
}//end main

string topSecret (string password)//replace all characters in password to an X
{
    string::size_type length;
    string::size_type pw;
    for (pw = 0; pw < password.length(); pw++)//for the duration of the password
    {
    }//end for loop
}//end topSecret

topSecret() function 除了迭代字符串之外沒有做任何事情,並且它沒有返回任何值 - 你應該從中得到一個編譯警告。

未指定void作為其返回值的 function 必須始終返回某些內容,並且不這樣做會導致未定義的行為。 在這種情況下, operator<<()嘗試打印的 std::string 實例可能最終引用了無效的 memory,從而導致崩潰。

僅供參考,任何時候你不理解 C++ function,你可以谷歌它,你應該在 cplusplus.com 彈出窗口找到一個很好的解釋。 這就是我得到我要告訴你的信息的地方。

編輯:正如另一個所說,cppreference.com 也應該出現,這也是看的地方。 忘記加了,哈哈

string::replace需要一個開始 position、一個長度和一個替換它的字符串。

您似乎想要的是一個 function 可以接受輸入值,並將其替換為您想要的任何值。 在這種情況下,您似乎想替換任何不是“-”的數字或字符,對嗎?

在這種情況下,我會創建一個 function,它接受一個字符串引用、一個“shouldReplace”function,以及一個將其替換為輸入的值。

您說您是初學者,所以以防萬一,我將解釋什么是參考。 本質上,如果您將變量傳遞到 function 並更改它,那么您實際上不會更改該變量,您將更改該變量的副本。 這稱為“按值傳遞”。 如果您改為通過引用傳遞,那么您所做的任何更改實際上都會影響您所做的事情。

我們的 function 將接收輸入字符串並對其進行修改,因為這是最簡單的路線,因為string::replace已經這樣做了。

接下來要解釋的是如何將function作為參數傳遞。 再說一次,既然你說你是初學者,我假設你不知道這一點。 函數可以存儲在變量中並像參數一樣傳入。 我們想要創建一個 function 給定一個字符,它會產生一個 boolean 來判斷該字符是否應該被替換,然后我們想將它傳遞給我們的替換 function。

現在是肉和土豆; 更換 function。

首先,我們將使用我提到的參數聲明 function:

#include <functional>
#include <string>

void conditionalReplaceWith(
        string &str, std::function<bool(char)> test, std::string repWith) {
    ...
}

請注意,要獲取字符串引用,我們使用&str並獲取 function,我們使用標准庫std::function的一部分,我們聲明它返回一個bool並將一個char作為參數。

這意味着當我們傳入 function 時,它應該如下所示:

bool testFuncToPassIn(char c) {
    ...
}

現在我們有了一個 function,讓我們填寫它。

我們想遍歷每個字符並測試它是否是我們要替換的字符。 如果是,那么我們替換它。 如果不是,那么我們繼續。

使用stringstream有更好的方法,但由於您暗示您正在嘗試執行string::replace ,因此我使用了它。

我也會使用 const 引用,但由於您是初學者,所以此時不值得解釋。 你還不需要知道。

#include <functional>
#include <string>

void conditionalReplaceWith(
        string &str, std::function<bool(char)> test, std::string repWith) {
    // Loop over every character. This will work even after modifying str
    for(int pos = 0; pos < str.length(); pos++) {
        if(test(str[pos])) { // Check if the character should be replaced
            str.replace(pos, 1, repWith); // Replace it! Increases str.length()
        }
    }
}

現在我們需要我們的測試函數:

bool isNotDash(char c) {
    return c != '-';
}

讓我們把它們放在一起:

#include <iostream>
#include <functional>
#include <string>

void conditionalReplaceWith(
        string &str, std::function<bool(char)> test, std::string repWith) {
    // Loop over every character. This will work even after modifying str
    for(int pos = 0; pos < str.length(); pos++) {
        if(test(str[pos])) { // Check if the character should be replaced
            str.replace(pos, 1, repWith); // Replace it! Increases str.length()
        }
    }
}

bool isNotDash(char c) {
    return c != '-';
}

int main() {
    std::string name, social, userName, password;
    std::cout << "Enter your first name, Social Security number (digits only), userID (no spaces within ID), and password (no spaces within password) - with a space between each entry: ";
    std::cin >> name >> social >> userName >> password;
    
    conditionalReplaceWith(social, isNotDash, "X");
    ...
}

最后,如果你想讓你的最高機密 function 使用conditionalReplaceWith ,你可以這樣做:

std::string topSecret(std::string password) {
    conditionalReplaceWith(password, [](char c) { return true; }, "X");
    return password;
}

那個小[](char c) { return true; } [](char c) { return true; }是一個匿名的 function。 它在那里聲明了一個 function。

無論如何,這不會更改密碼,因為請記住,密碼是按值傳遞的。 在這里修改它就像說std::string passwordCopy(password)並首先復制它。

是的。 那里有 go。

好的:] 好吧,我以一種非常有意義的方式將其發送給 output,這要感謝您的貢獻和我的一些閱讀。 我還去了 cppreference 網站閱讀更多內容。 非常感謝你的幫忙。 這是我的新的和改進的代碼..請讓我知道你們的想法...

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

bool isNotDash(char);//prototype for isNotDash
string xOut(string);//prototype for xOut function
string topSecret(string);//prototype for topSecret function after main

int main()
{
    //Top Secret Input
    string name, social, userName, password;
    cout << "Enter your first name, Social Security number (000-00-000 format), userID (no spaces within ID), and password (no spaces within password) - with a space between each entry: ";
    cin >> name >> social >> userName >> password;
    cout << "Let's cover some of this up, shall we..." << endl;
    cout << "Name: " << name << endl;
    cout << "SSN: " << xOut(social) << endl;//calls xOut function to use as the output
    cout << "UserID: " << userName << endl;
    cout << "Password: " << topSecret(password) << endl;//calls topSecret function to use as output

    return 0;
}//end main

bool isNotDash(char n) //checks to see if within string social, is it a dash or number
{
    return n != '-'; // return any character that is not a dash - which would be a number
}//end isNotDash

string xOut(string social) // replace with X
{
    for(int x = 0; x < social.length(); x++)//loop through string
        {
            if(isNotDash (social.at(x)))// calls isNotDash function to check to see if character, that is not a dash, should be replaced
        {
            social.replace(x, 1, "X"); // start at position x, iterate, and x it out
        }//end if
    }
    return social;
}//end xOut function



string topSecret (string password)//replace all characters in password to an X
{
    string::size_type length;
    for (int pw = 0; pw < password.length(); pw++)//declare and initialize integer pw to 0, as long as it does not exceed the length of password - loop
    {
        password.replace(pw, 1, "X");//start at pos pw, iterate, and replace with x
    }//end for loop
    return password;
}//end topSecret

暫無
暫無

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

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