为什么我的简单字符串不正确构造?

时间:2014-04-02 03:14:31

标签: c++ string

我有一个简单的函数,可以构建一个简单的电影'的字符串表示。宾语。我这样做......

string Movie::getDisplayText() {
  ostringstream oss;
  oss << "Title: " << this->getTitle() << "\tYear: "+this->getYear() << "\tGenre: " << this->getGenre();
  string ret = oss.str();

  return ret;
}

但是构建和返回的字符串看起来像这样......

\�tle: Star Wars�B
    Genre: Science-Fiction

当我添加此行以测试时,值是有效的......

cout << "DEBUG Title: " << this->getTitle() << "\tYear: "+this->getYear() << "\tGenre: " << this->getGenre() << "\n" << endl;

...输出到&#39; cout&#39;一个正确的字符串,所以我知道这些值都已正确初始化...

DEBUG title='Star Wars'; year='1977'; genre='Science-Fiction';

我的ostringstream代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

你有这个:

string Movie::getDisplayText() {
  ostringstream oss;
  oss << "Title: " << this->getTitle() << "\tYear: "+this->getYear() << "\tGenre: " << this->getGenre();
  string ret = oss.str();

  return ret;
}

应该是

string Movie::getDisplayText() {
  ostringstream oss;
  oss << "Title: " << this->getTitle() << "\tYear: " << this->getYear() << "\tGenre: " << this->getGenre();
  string ret = oss.str();

  return ret;
}

在\ t之后没有区别:原因是将字符串文字和int一起添加不会导致连接。