2012-10-27 124 views
1

我想連接一些字符串,但它在一個而不是另一箇中起作用。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** 

希望它給出更清晰的例子。

更新:

我想我可能已經發現該問題是由於該文本文件。我試圖創建一個新的文本文件,裏面有一些隨機線,看起來工作正常。但是如果我嘗試讀取原始文件,它會給我輸出錯誤。仍然試圖讓我的頭在這附近。

然後我試圖將原始文件的內容複製到新文件,它似乎工作正常。不太確定這裏有什麼問題。將繼續測試,並希望它工作正常。

感謝您的幫助!欣賞它!

+11

請提供更完整的代碼。 – user763305

+0

您的示例代碼在此正常工作(MSVC)。你在用什麼編譯器? –

+0

@ user1778855,顯然你做錯了什麼,但沒有人能從你發佈的信息中知道它是什麼。請發佈*完整*程序,說出輸入內容,說出輸出內容,並說出你期望輸出的內容。不要只是說'它給了我錯誤的答案',那不會告訴任何人。做到這一點,你會很快回答你的問題。 – john

回答

1

我得到的輸出作爲誰問原來的問題的第一章一樣:

$ ./a.out hello world 
Enter code: good 
goodworld 
worldly 

的這裏的問題是文本文件的內容。就我的例子而言,文本文件中的最初7個字符是:「快速」。但緊接着的是7個退格字節(十六進制08)。這是內容看起來像在Emacs什麼:

quickly^H^H^H^H^H^H^H 

那麼這是怎麼造成的爛攤子?

那麼串聯操作實際上正常工作。如果你這樣做:

std::cout << "string length: " << temp.size() << "\n"; 

...你的答案19它是由以下部分組成: 「快」(7)+ 7個退格字符+ 「世界」(5)。您觀察到的覆蓋效應是在將這19個字符串打印到控制檯時引起的:它是控制檯(例如xterm),它將退格序列解釋爲「將光標移回左邊」,從而刪除較早的字符。如果您將輸出傳輸到文件,您將看到實際生成的完整字符串(包括退格)。

要解決此問題,您可能需要驗證/更正來自該文件的輸入。在C/C++環境中可以使用通常可用的函數,例如isprint(int c), iscntrl(int c)

更新:如其他響應者所述,其他ASCII控制字符也會具有相同的效果,例如回車(十六進制0D)也會將光標移回左側。

1

如果我編譯這個

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

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. 

    //However, I read some lines from the file. 
    ifstream infile; 

    string f3 = "temp.txt"; 
    string r; 
    string temp; 

    infile.open (f3.c_str()); 

    while (getline (infile, r)) { 
     temp = r + code; 
     cout << temp << endl; 
    } 
    // The above would give me the wrong concatenation. 
    infile.close(); 
    return 0; 
} 

它編譯和運行完美。這在你的電腦上做了什麼?如果失敗,我們可能需要比較我們的temp.txt的內容。

(這應該是而不是回答的評論,但它太長對不起。)