奇怪的std::cout错误

C++: Weird std::cout error

本文关键字:cout 错误 std      更新时间:2023-10-16

我认为这将是一个相对简单的事情:用尾斜杠附加"www.google.ie",并用"http://"前置,结果是一个值为"http://www.google.ie/"的字符串。不,这不是家庭作业……(我知道)

下面是我的代码:
std::string line=split1[0];   //split1[0] is "Host: www.google.ie"
std::vector<std::string> split2;
boost::split(split2,line,boost::is_any_of(" "));
boost::erase_all(split2[1],"n");
std::cout<<"split2[1]:"<<split2[1]<<std::endl;   //outputs www.google.ie ok
fURL="http://"+split2[1]+"/";
//fURL="http://www.google.ie/";   //this is what I want fURL to be!
std::cout<<std::endl;   //just for some testing
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"fURL:"<<fURL<<std::endl;   //should output: http://www.google.ie/?

这是我奇怪的输出:

split2[1]:www.google.ie


/URL:http://www.google.ie

我不知道'/URL:'中的'/'是从哪里来的。就好像我指定的尾斜杠以某种方式被加到了前面。我真的不明白这是怎么可能的…

在Linux上使用g++ 4.5.2

如有任何见地,不胜感激。

提前致谢

我猜这一行

//split1[0] is "Host: www.google.ie"

和你说的不一样。例如,如果你通过http获取,你会有

//split1[0] is "Host: www.google.iern"

,删除n后为

//split1[0] is "Host: www.google.ier"

则fURL为

卷起= " http://" + split2[1] +"/";//http://www.google.ie r/

std::cout<<"fURL:"<<fURL<<std::endl

将打印

卷起:http://www.google.ie

转到第一列(r)并打印'/'覆盖第一个字符'f'

这是你的代码,放在一个小程序中,只有一个调用你的代码包装在foo()函数中。它像你期望的那样工作,没有像你观察到的那样奇怪。如果我遇到像你这样的问题,我总是用那些"奇怪"的代码写一个小程序。正如其他人所暗示的那样,一定有别的东西使事情出错。这里,试一下:

#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/erase.hpp>
using namespace std;
void foo(const char **split1)
{
   std::string line = split1[0];   //split1[0] is "Host: www.google.ie"
   std::vector<std::string> split2;
   boost::split(split2,line,boost::is_any_of(" "));
   boost::erase_all(split2[1],"n");
   std::cout<<"split2[1]:"<<split2[1]<<std::endl;   //outputs www.google.ie ok
   string fURL="http://"+split2[1]+"/";
   //fURL="http://www.google.ie/";   //this is what I want fURL to be!
   std::cout<<std::endl;   //just for some testing
   std::cout<<std::endl;
   std::cout<<std::endl;
   std::cout<<std::endl;
   std::cout<<std::endl;
   std::cout<<"fURL:"<<fURL<<std::endl;   //should output: http://www.google.ie/?
}
int main()
{
    const char *split = "Host: www.google.ie";
    const char *split1[1];
    split1[0]  = split;
    foo(split1);
    return 0;
}