转换为字符串的数字向量与文本文件中的字符串之间的这种比较不起作用?

This comparison between a vector of numbers converted to a string and a string from a text file is not working?

我正在尝试将双精度向量与一串数字进行比较。在下面的代码中,我只是从 txt 文件中复制了一行并将其放入向量中,将每个数字转换为一个字符串并将其连接起来。 然后程序从相同的 txt 文件中读取具有完全相同格式和间距的行。但是,根据我的代码,它找不到它..任何人有什么想法吗?打印时的 concanstring 与我从中复制的位置完全相同。如果我在 if 之前的最后一个循环中 cout newstring,它会打印出与文本文件中完全一样的所有内容。 看起来像:

5 0 4 0 2 6 0 1 5 1 4

-0.00021 -0.00321 0.00045 0.00089 0.00435 0.00065

1 5 8 3 0 1 4 8 9 7 2

等等。

int main()
{
std::vector <int> momentum{ 5,  0 , 4  ,2 , 6 , 0 , 1 , 5 , 1 , 4 };
std::string newstring;
std::string concanstring;
std::ifstream datafile("thedata.txt");

for (int i = 0; i < momentum.size(); i++)
{
    std::ostringstream newobj;
    newobj << momentum[i];
    concanstring += newobj.str();
    concanstring += " ";
}
std::cout  << concanstring;

while (std::getline (datafile, newstring))
{
    int x = newstring.compare(concanstring);
    if (x != 0) std::cout << "fail";
    else std::cout << "success";        
}      
}

你在 concanstring 的末尾有一个额外的 space 因为比较失败,你必须像这样删除那个额外的 space

int main()
{
std::vector <int> momentum{ 5,  0 , 4  ,2 , 6 , 0 , 1 , 5 , 1 , 4 };
std::string newstring;
std::string concanstring;
std::ifstream datafile("thedata.txt");

for (int i = 0; i < momentum.size(); i++)
{
    std::ostringstream newobj;
    newobj << momentum[i];
    concanstring += newobj.str();
    concanstring += " ";
}
concanstring.pop_back();
std::cout  << concanstring;

while (std::getline (datafile, newstring))
{
    int x = newstring.compare(concanstring);
    if (x != 0) std::cout << "fail";
    else std::cout << "success";        
}      
}

而是连接字符串读取 int 并比较它。

int findFileNrWith(std::istream& in, const std::vector<int>& data)
{
    int lineNr = 0;
    std::string l;
    while (getline(in, l)) {
        std::istringstream line{l};
        auto stream_begin = std::istream_iterator<int>{line};
        auto stream_end = std::istream_iterator<int>{};

        auto result = std::mismatch(data.begin(), data.end(), 
                                    stream_begin, stream_end);

        if (result == std::make_pair(data.end(), stream_end))
           return lineNr;
        ++lineNr;
    }
    return -1;
}

找到了一种可行的方法,而且它的代码更少,所以我很高兴 :D 如果有人认为这是一种不好的方法,请告诉我:)

int main()
{
std::vector <int> momentum{ 5,  0 , 4  ,2 , 6 , 0 , 1 , 5 , 1 , 4 };
std::vector <int> newmomentum{};
std::string newstring;
std::ifstream datafile("thedata.txt");
int moment{};

while (std::getline (datafile, newstring))
{
    std::stringstream nextstring(newstring);
    for (int i = 0; i < momentum.size(); i++)
    {
        nextstring >> moment;
        newmomentum.push_back(moment);
    }
    if (newmomentum == momentum)
    {
        std::cout << "success";
    }
    else newmomentum.clear();        
} 
}