【发布时间】:2016-02-17 12:11:32
【问题描述】:
我正在编写一个任务,基本上,我有一个客户端和服务器进行通信。为此,我在服务器端使用字符串流来处理请求(以字符串的形式出现)并帮助构建字符串响应。服务器端拥有一个对象 (FileManager),其中包含多个 MultimediaFile 对象,每个对象都包含有关它们自己的信息。这个信息可以通过一个方法打印出来,其中一个参数是ostream&。
为了从客户端获取请求,stringstream 工作得很好,但是当我将它传递给方法时,由于某种原因它不会读取内容(而如果我传递 std::cout 它工作得很好) .我认为这与 stringstream 使用
我知道我可以简单地将我需要的关于对象的信息存储在一个字符串或类似的东西中(而不是使用 ostream&),但教授希望该方法直接打印到传递的 ostream,而不是返回一个字符串。
代码如下:
bool processRequest(TCPServer::Cnx& cnx, const string& request, string& response)
{
bool changeData = false;
if (request == "delMedias" || request == "delGroups") changeData = true;
TCPServer::Lock lock(cnx, changeData);
cerr << "request: '" << request << "'" << endl;
string operation = "";
string filename = "";
stringstream iss;
iss.str(request); //next few lines get request info, works just fine!
if (iss.rdbuf()->in_avail() != 0)
iss >> operation;
if (iss.rdbuf()->in_avail() != 0)
iss.get();
if (iss.rdbuf()->in_avail() != 0)
getline(iss, filename);
iss.str("");
if (operation.size() == 0 || filename.size() == 0) return false;
response = "";
if (operation.compare("print") == 0)
{
filem.showFile(filename, iss); //Problem here!!!!
if (iss.rdbuf()->in_avail() != 0) //iss is always empty
{
response = iss.str();
response = "Print info: " + response;
}
else
response = "No info received!";
}
else if (operation.compare("play") == 0)
{
filem.playFile(filename);
response = "File played!";
}
else
response = "Operation not valid";
cerr << response << endl;
return true;
}
TCPServer 是教授提供的一个让事情变得更简单的类,但基本上客户端发送一个字符串 request 并且在这个函数的最后,接收一个字符串响应来自服务器。 filem 是 FileManager 类对象,下面是 showFile 方法的代码:
void FileManager::showFile(string name, ostream& s)
{
if (mfiles.find(name) != mfiles.end())
mfiles[name]->printFile(s);
}
mfiles 是字符串到 MultimediaFile* 的映射(特别是 MultimediaFile 的 std::shared_ptr,但无论如何)。基本上,这段代码检查是否有一个名为 name 的文件,如果有,则调用 printFile(s) 方法,这里的 s 是串流。这是方法的代码:
void MultimediaFile::printFile(ostream& s) const
{
s << "File name: " << name << "\tFilepath: " << filepath << "\n";
}
name 和 filepath 是 MultimediaFile 类的实例变量。所以,是的,我希望我的字符串流能够接收到这些信息,然后在方法调用之后,这些信息将用于在代码的主要部分构建 response 字符串。然而,情况并非如此,并且字符串流始终为空(并且由于这适用于 std::cout,因此问题不在于 MultimediaFile 对象中的数据)。
再次,我会说 stringstream 在通过
如果您需要任何其他信息,请告诉我。提前致谢!
【问题讨论】:
-
顺便说一句:你为什么用
operation.compare("print") == 0而不是operation == "print"? -
我不认为它应该表现不同并且不能重现这样的问题。您确定代码路径相同吗?
showFile中的if在cout和stringstream变体之间的决定是否不同? -
是的,路径是一样的。我尝试使用gdb,它直接进入那段代码,所以它应该是一样的,对吧?
-
另外,为了比较,我承认我不记得为什么了,哈哈。我想我在使用 == 时收到了某种警告。我现在会再试一次检查,但不幸的是我正在上课,所以我稍后必须给你一个更好的答案。
-
and it goes straight to that bit of code哪个位?您应该尝试提供重现问题的代码。鉴于当前信息,我(可能还有其他人)无法重新创建它。
标签: c++ stringstream ostream