簡體   English   中英

使用 cin.getline(.) 將 char 數組轉換為字符串

[英]Convert char array to a string with cin.getline(.)

大家好,我的問題是如何將 char 數組轉換為字符串。 這是我的代碼:

#include<iostream>
using namespace std;

int main()
{
    while (true) {
        char lol[128];
        cout << "you say >> ";
        cin.getline(lol,256);
        cout << lol << endl;;
    }
    return 0;
}

所以我想將 lol 轉換為像“stringedChar”這樣的字符串變量(如果那是英語 lol),所以我可以執行以下操作:


        string badwords[2] = {"frick","stupid"};
        for (int counter = 0; counter < 2;counter++) {
            if(strigedChar == badwords[counter]) {
             bool isKicked = true;
             cout << "Inappropriate message!\n";
            }
        }

對不起,我只是一個 c++ 初學者哈哈

做這樣的事情:

作為字符大聲笑[128]; 成字符串,如:std::string str(lol);

線路:cin.getline(lol,256); <--> 應該改為 cin.getline(lol,128)

只需在std::string object 上調用std::getline()而不是搞亂char數組,並將std::set<std::string>用於badwords詞,因為測試集成員資格很簡單:

#include <iostream>
#include <set>
#include <string>

static std::set<std::string> badwords{
    "frick",
    "stupid"
};

int main() {
    std::string line;

    while (std::getline(std::cin, line)) {
        if (badwords.count(line) != 0) {
            std::cout << "Inappropriate message!\n";
        }
    }

    return 0;
}

請注意,這會測試整行是否等於集合的任何元素,而不是測試該行是否包含集合的任何元素,但您的代碼似乎無論如何都試圖執行前者。

首先,您的代碼中有錯誤。 您正在分配 128 個char的數組,但您告訴cin.getline()您分配了 256 個char 所以你有一個緩沖區溢出等待發生。

也就是說, std::string具有接受char[]數據作為輸入的構造函數,例如:

#include <iostream>
using namespace std;

int main()
{
    while (true) {
        char lol[128];
        cout << "you say >> ";
        cin.getline(lol, 128);
        string s(lol, cin.gcount());
        cout << s << endl;;
    }
    return 0;
}

但是,您確實應該使用std::getline()代替,它填充std::string而不是char[]

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

int main()
{
    while (true) {
        string lol;
        cout << "you say >> ";
        getline(cin, lol);
        cout << lol << endl;;
    }
    return 0;
}

暫無
暫無

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

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