我正在开发一个使用函数和指针在用户输入句子后用空格替换逗号的程序。
但是,当我运行该程序时,出现上述错误,并显示另一个错误;
“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, ' ');
};
最佳答案
您无需在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");
};
关于c++ - 初始化无法从const char [3]转换为std::string *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47935613/