【问题标题】:Convert char array to a string with cin.getline(.)使用 cin.getline(.) 将 char 数组转换为字符串
【发布时间】:2020-05-06 20:52:15
【问题描述】:

大家好,我的问题是如何将 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++ 初学者,哈哈

【问题讨论】:

  • 为什么不用字符串开头string lol; getline(cin, lol);简单不?
  • 但是如果因为某种原因你真的需要转换,那也不难,string stringedChar = lol;
  • 还会修复将 256 个字符读入 128 个字符数组的错误
  • 另外,将badwords 设为std::set&lt;std::string&gt;,然后您就可以测试badwords.count(lol) != 0
  • 对我不起作用。它也忽略空格吗?就像它在看到空格时不会停止存储东西

标签: c++ string oop char


【解决方案1】:

做这样的事情:

作为字符大声笑[128]; 转换成字符串,如:std::string str(lol);

行:cin.getline(lol,256); 应该改成cin.getline(lol,128)

【讨论】:

    【解决方案2】:

    只需在std::string 对象上调用std::getline(),而不是搞乱char 数组,并使用std::set&lt;std::string&gt; 代替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;
    }
    

    请注意,这将测试整行是否等于集合的任何元素,该行包含集合的任何元素,但您的代码似乎无论如何都试图执行前者.

    【讨论】:

    • 在 C++20 中,std::set 有一个新的contains() 方法:if (badwords.contains(line))
    • @RemyLebeau 是的,我看到了,但它还没有在任何地方都可用,并且不太可能具有显着不同的性能特征。
    • 是的,但我只是为了完整性而提及它。
    【解决方案3】:

    首先,您的代码有误。您正在分配 128 个chars 的数组,但您告诉cin.getline() 您分配了 256 个chars。所以你有一个缓冲区溢出等待发生。

    也就是说,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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 2019-08-04
      • 2013-04-25
      • 2012-11-04
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多