我正在製作一個C++程序,它將用「%20」替換char數組中的所有空格。 例如,「這是一些有空格的文本」將被轉換爲「This%20is%20some%20text%20with%20some%20spaces」由循環內部函數返回的打印指針
請在程序中註明哪些線路工作不正常。
替代程序在此程序中的函數將指針指向char數組和字符串的大小。 然後方法創建新的字符數組替換空格和函數返回指針替換字符數組。
該程序中的問題是在main函數中打印char數組,其指針由替換器返回。
「replaced」是指向替換字符串的指針變量。在主函數我試圖用「替換」指針來打印字符數組。
如果我手動打印一切,它工作正常。 例如,如果我這樣做:cout << *replaced << *(replaced+1) << *(replaced+2)
.... 整個字符串將被打印。
但內部循環它給了我垃圾值。請讓我知道我在代碼中犯了什麼錯誤。謝謝。
#include <iostream>
using namespace std;
char * replacer(char * text, unsigned int size)
{
int space_count = 0, i = 0, new_size = 0;
cout << "Given text : ";
for(i = 0;i < size;i++)
{
cout << *(text + i) ;
char temp = *(text + i);
if (temp == ' ')
{
space_count++;
}
}
cout << endl;
cout << "Number of spaces in given text : " << space_count << endl;
new_size = size + (2 * space_count);
char replaced_string[new_size];
int counter = 0 ;
for(i = 0 ;i < size; i++)
{
char temp = *(text + i);
if(temp == ' ')
{
replaced_string[counter++] = '%';
replaced_string[counter++] = '2';
replaced_string[counter++] = '0';
}
else
{
replaced_string[counter++] = temp;
}
}
cout << "in replacer method : " << replaced_string << endl;
char * pointer_to_replaced;
pointer_to_replaced = replaced_string;
return pointer_to_replaced;
}
int main()
{
int t;
char original[] = "This is some text with some spaces";
char * original_pointer = original;
char *replaced;
replaced = replacer(original_pointer, sizeof(original));
//cout << *(replaced) << *(replaced+1) << *(replaced+2) << *(replaced+3) << *(replaced+4) << endl;
// ABOVE LINE WORKS FINE
for(t=0;t<20;t++)
{
cout<<*(replaced+t); // THIS IS NOT WORKING PROPERLY
}
cout <<endl;
return 0;
}
這幾乎已經用'std :: string :: replace'完成了。 – ghostofstandardspast
由於您稱之爲C++程序,因此我建議刪除C組件,例如字符數組。使用'std :: string'。這是你的錯誤來自的地方。 –
'replaced_string'不是空終止的。 – 0x499602D2