2016-03-06 16 views
1

低於check是字符串,而temp1->data是整數。我想將temp1->data插入check。所以我輸入intconst char*。這使代碼warning : cast to pointer from integer of different size [-Wint-to-pointer-cast]如何在C++中使用插入函數將整數插入到字符串中?

部分:

temp1 = head; 
    std::string check; 
    check = ""; 
    int i = 0; 
    while(temp1 != NULL) 
    { 
    check.insert(i, (const char*)temp1->data);// here is the warning 
    temp1 = temp1->next; 
    ++i; 
    } 

我想知道我有使用插入功能插入整數(temp1->data)轉換爲字符串(check)什麼其他的選擇,什麼是警告的實際效果[-Wint-to-pointer-cast]在我的代碼上。

點:

  1. 數據是整數,其次是指向節點
  2. 我想要實現的功能,以檢查是否含有單位數鏈表是迴文與否。是的,我知道其他方法,但我只是想通過這種方法來實現。
  3. 這裏我想將鏈接列表的所有數據存儲到一個字符串中,並直接檢查字符串是否是迴文。

此問題看起來可能與this重複。但它不是,我在這裏明確要求使用包含在字符串類中的插入函數將整數插入到字符串中。

PS:使用std::to_string(temp1->data) gives me error ‘to_string’ is not a member of ‘std’

+0

你想做什麼?你是否願意將一個整數插入到一個字符串或其他東西? – surajsn

+0

數據的性質是什麼,以及爲什麼要嘗試這樣做? – StoryTeller

+0

你能更詳細地描述你想做什麼嗎?例如。你試圖讓字符串包含數字的文本表示,或其他東西 –

回答

0

首先,這裏有一種方法可以將整數轉換爲字符串,而不需要太多工作。您基本上創建一個流,將int清理到它,然後提取您需要的值。底層代碼將處理骯髒的工作。

這裏有一個簡單的例子:

stringstream temp_stream; 
int int_to_convert = 5; 

temp_stream << int_to_convert; 
string int_as_string(temp_stream.str()); 

下面是關於這個解決方案的更多信息,並選擇,如果你想知道更多: Easiest way to convert int to string in C++

關於演員的你正在做的影響,行爲將是未定義的,因爲您將char *設置爲int值。效果不會將int值轉換爲一系列字符,而是將系統解釋爲char數組的第一個字符的位置與int的值的位置設置爲內存位置。

+1

這是一件快速而簡單的事情。 –

+0

@ n.m。公平的批評,更新語言以更真實地描述提供的解決方案。 – mabeechen

1

您可以使用std::to_string函數將整數轉換爲字符串,然後使用std::string上的插入函數將其插入到字符串中。

std::string check; 
check = ""; 
int i = 0; 

check.insert(i, std::to_string(10)); 

您收到錯誤"to_string is not a member of std"的原因是可能是因爲你沒有include <string>頭。

相關問題