我想連接一些字符串,但它在一個而不是另一箇中起作用。C++中的字符串串聯問題
工作:我採取了2個參數,然後做到這一點。 a =你好,b =世界
string concat = a + b;
輸出將是hello世界沒有問題。
不工作:我從文件讀取並連接到第二個參數。假定來自文件的字符串是abcdefg。
string concat = (string from file) + b;
,這讓我worldfg。
而不是連接,字符串從b覆蓋初始字符串。
我已經嘗試了一些其他方法,如使用stringstream,但它不工作。
這是我的代碼。
int main (int nArgs, char *zArgs[]) {
string a = string (zArgs [1]);
string b = string (zArgs [2]);
string code;
cout << "Enter code: ";
cin >> code;
string concat = code + b;
}
// The output above gives me the correct concatenation.
// If I run in command prompt, and do this. ./main hello world
// then enters **good** after the prompt for code.
// The output would be **goodworld**
但是,我從文件中讀取了一些行。
string f3 = "temp.txt";
string r;
string temp;
infile.open (f3.c_str());
while (getline (infile, r)) {
// b is take from above
temp = r + b;
cout << temp << endl;
}
// The above would give me the wrong concatenation.
// Say the first line in temp.txt is **quickly**.
// The output after reading the line and concatenating is **worldly**
希望它給出更清晰的例子。
更新:
我想我可能已經發現該問題是由於該文本文件。我試圖創建一個新的文本文件,裏面有一些隨機線,看起來工作正常。但是如果我嘗試讀取原始文件,它會給我輸出錯誤。仍然試圖讓我的頭在這附近。
然後我試圖將原始文件的內容複製到新文件,它似乎工作正常。不太確定這裏有什麼問題。將繼續測試,並希望它工作正常。
感謝您的幫助!欣賞它!
請提供更完整的代碼。 – user763305
您的示例代碼在此正常工作(MSVC)。你在用什麼編譯器? –
@ user1778855,顯然你做錯了什麼,但沒有人能從你發佈的信息中知道它是什麼。請發佈*完整*程序,說出輸入內容,說出輸出內容,並說出你期望輸出的內容。不要只是說'它給了我錯誤的答案',那不會告訴任何人。做到這一點,你會很快回答你的問題。 – john