簡體   English   中英

初始化無法從const char [3]轉換為std :: string *

[英]Initializing cannot convert from const char [3] to std::string *

我正在開發一個使用函數和指針在用戶輸入句子后用空格替換逗號的程序。

但是,當我運行該程序時,出現上述錯誤,並顯示另一個錯誤;

“ 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");    
};

暫無
暫無

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

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