いくつかの文字列を連結しようとしていますが、ある文字列では機能しますが、別の文字列では機能しません。
作業: 2 つの引数を取り、これを実行します。a = こんにちは、b = 世界
string concat = a + b;
出力は問題なく hello world になります。
機能しない: ファイルから読み取り、2 番目の引数と連結します。ファイルからの文字列が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**
より明確な例が得られることを願っています。
アップデート:
問題の原因がテキスト ファイルにあることがわかったのではないかと思います。内部にいくつかのランダムな行を含む新しいテキスト ファイルを作成しようとしましたが、正常に動作しているようです。しかし、元のファイルを読み取ろうとすると、間違った出力が返されます。まだこれに頭を悩ませようとしています。
次に、元のファイルの内容を新しいファイルにコピーしようとしましたが、うまく機能しているようです。ただし、ここで何が問題なのかよくわかりません。引き続きテストを行いますが、うまくいくことを願っています。
助けてくれてありがとう!感謝します!