C 中的字符串串联问题

String concatenation issue in C++

本文关键字:问题 字符串      更新时间:2023-10-16

我正在尝试加入一些字符串,但它不起作用,但不起作用。

工作:我接受了2个参数,然后执行此操作。a =你好,b = world

string concat = a + b;

输出将是Hello World没问题。

不起作用:我从文件中读取并与第二个参数串联。假设文件中的字符串是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**

希望它提供更清楚的例子。

更新:

我认为我可能已经发现问题是由于文本文件引起的。我试图创建一个带有一些随机线的新文本文件,并且看起来正常。但是,如果我尝试读取原始文件,它会给我错误的输出。仍在试图把我的头放在这个方面。

然后,我试图将原始文件的内容复制到新文件中,并且似乎工作正常。不太确定这里有什么问题。将继续测试,希望它可以正常工作。

感谢您的所有帮助!感谢它!

我得到的输出与问原始问题的CHAP相同:

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

这里的问题是文本文件的内容。就我的示例而言,文本文件中的最初7个字符是:"快速"。但是,紧随其后的是7个Backspace字节(十六进制08)。这就是emacs中的内容的样子:

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

那么这是如何导致混乱的?

串联操作实际上可以正常工作。如果您这样做:

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

...您得到的答案19由:"快速"(7) 7个backspace chars " world"(5)。当您将此19个Char字符串打印到主机上时,您观察到的覆盖效果是引起的:正是控制台(例如xterm)将backspace序列解释为"将光标移回左侧",从而删除了早期的字符。相反,如果您将输出输送到文件,则实际上会看到完整的字符串(包括背景)。

为了解决这个问题,您可能需要验证/更正文件中的输入。C/C 环境(例如isprint(int c), iscntrl(int c))中通常可用的功能可以使用。

更新:正如另一位响应者所提到的,其他ASCII控制字符也将具有相同的效果,例如,运输返回(HEX 0D)也会将光标移至左侧。

如果我编译了此

#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的内容。

(这应该是评论,而不是答案,但这太长了。对不起。)