我正在從一組數據庫字段構建一個固定長度的記錄的C++應用程序。我正在編寫一個函數,它將接受輸出記錄爲char*
,要寫入的字符串以及該字段的總長度。該函數的目的是將字符串複製到char指針的當前位置,然後用空格填充剩餘的長度。這是我正在做的一個簡單的例子。我可以增加傳遞給函數的char *嗎?
void writeOut(char* output, string data, const int length) {
if ((int) data.size() > length) {
//Just truncate it
data = data.substr(0, length);
}
int index = 0;
while (index < (int) data.size()) {
*output++ = data[index++];
}
while (index++ < length) {
*output++ = ' ';
}
}
int test() {
char output[100];
writeOut(output, "test1", 10);
writeOut(output, "test2", 10);
writeOut(output, "test3test4test5", 10);
cout << output;
}
我希望看到類似這樣的內容。
test1 test2 test3test4
相反,我得到的是...
test3test4
因此它遞增char*
函數內,但僅限於功能。當功能結束時,char*
就在它剛剛開始的地方。是否有可能傳遞一個指針,使指針在調用函數中更新?
如果你不能說,我很新的C++。任何建議將不勝感激。
只要確保傳入一個char *,而不是char [],因爲你不能增加數組的值。 – 2009-09-29 17:48:51
另外:這會破壞他的cout <<輸出行,除非他製作了指針的副本。你必須做一個char *指向輸出,然後使用它。 – 2009-09-29 18:39:37
謝謝。出於某種原因,我認爲你不能傳遞一個指針的引用。 – 2009-09-29 19:46:41