我使用一行輸入,它被一個空格分隔,並試圖將數據讀入兩個整數變量。將std :: string分割爲兩個const char * s導致第二個const char *覆蓋第一個
例如:「0 1」應該給child1 == 0
,child2 == 1
。
我正在使用的代碼如下:
int separator = input.find(' ');
const char* child1_str = input.substr(0, separator).c_str(); // Everything is as expected here.
const char* child2_str = input.substr(
separator+1, //Start with the next char after the separator
input.length()-(separator+1) // And work to the end of the input string.
).c_str(); // But now child1_str is showing the same location in memory as child2_str!
int child1 = atoi(child1_str);
int child2 = atoi(child2_str); // and thus are both of these getting assigned the integer '1'.
// do work
發生了什麼事是困擾我沒有盡頭。我使用Eclipse調試器(gdb)監視序列。當功能啓動時,child1_str
和child2_str
顯示具有不同的內存位置(他們應該)。在分割字符串separator
並獲得第一個值後,child1_str
按預期保持「0」。
但是,將值賦給child2_str
的下一行不僅會將正確的值分配給child2_str
,還會覆蓋child1_str
。我甚至不意味着字符值被覆蓋,我的意思是調試器顯示child1_str
和child2_str
在內存中共享相同的位置。
什麼是什麼?
1)是的,我很樂意聽取其他建議,將字符串轉換爲int - 這是我很久以前學會了如何學習的方式,而且我從來沒有遇到任何問題,所以不需要改變,但是:
2)即使有更好的方法來執行轉換,我仍然想知道這裏發生了什麼! 這是我的最終問題。所以,即使你提出了一個更好的算法,所選擇的答案將會是幫助我理解算法失敗的原因。
3)是的,我知道std :: string是C++,const char *是標準的C. atoi需要一個c字符串。我將它標記爲C++,因爲輸入將絕對來自我使用的框架的std :: string。
感謝您的雙頭答案。很有用。 –