【问题标题】:Initializing cannot convert from const char [3] to std::string *初始化不能从 const char [3] 转换为 std::string *
【发布时间】:2018-06-04 18:13:54
【问题描述】:

我正在开发一个程序,该程序使用函数和指针在用户输入句子后用空格替换逗号。

但是,当我运行程序时,我收到上述错误和另一个错误;

“C++“const char *”类型的值不能用于初始化“std::string *”类型的实体”

这个程序有问题,想知道这里是否有人可以在正确的方向上帮助我?

谢谢!

代码如下:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;




 void comma2blank(string* pString1);
 int main()

{

string* String1 = "  " ;

    cout << "Tell me why you like programming" << endl;
    getline(cin, *String1);

    comma2blank(String1);
    cout << " String 1 without comma is: " << *String1 << endl;

    delete String1;
    system("pause");

 };


 void comma2blank(string* pString1)
 {

pString1->replace(pString1->find(','), 1, 1, ' ');
pString1->replace(pString1->find(','), 1, 1, ' ');



 };

【问题讨论】:

    标签: c++ string function pointers error-handling


    【解决方案1】:

    您无需在main() 中创建字符串指针。您需要一个完整的字符串对象,您可以将其地址(指针)传递给您的函数,如下所示:

    int main()
    {
        string String1; // NOT a pointer!
    
        cout << "Tell me why you like programming" << endl;
        getline(cin, String1);
    
        comma2blank(&String1); // NOTE: pass by pointer using & (address of)
        cout << " String 1 without comma is: " << String1 << endl;
    
        // no need to delete anything here
    
        system("pause");    
    };
    

    【讨论】:

    • 祝福你,伙计,非常感谢你的帮助。我是编码新手,很抱歉这个新手问题。再次感谢!
    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 2018-08-23
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多