c++中find()命令的问题

Problems with find() command in c++

本文关键字:命令 问题 find c++      更新时间:2023-10-16

我试图拔出firstName字符串,但是我得到非常奇怪的输出。

样本数据:75428爱德华·马斯顿

想要输出:Marston Edward 75428

输出接收:马斯顿,爱德华·爱德华75428

代码:

ifstream textFile("NameZip.txt");//File initializer
int counter = 0; //Used to cycle data into struct[] implementData. Avoiding a longer more memory hungry alternative since we know the file is going to be 20 lines long
int tmpZip;
string tmpString;
personData implementData[20];//creates object for structure
if(textFile.is_open())//checks to make sure file exists in same folder to avoid errors
{while(getline(textFile,tmpString))
{
    stringstream convert(tmpString.substr(0,6));
    convert >> tmpZip; //pulls out the Zipcode
    string firstName = tmpString.substr(tmpString.find(" ") +1,tmpString.find(","));//pulls out the first name
    string lastName = tmpString.substr(tmpString.find(",")+2); //pulls out last name
    implementData[counter++] = {tmpZip,firstName,lastName}; //sets value for that tab in the structure personData
}}else
    cout << "There was a problem reading from the textFilenPlease make sure the file is in the same folder as the .cpp program" << endl;
printData(implementData);
return 0;

不仅仅是这一个数据,First Name的所有数据似乎都在第13个字符处停止,而不是在逗号处停止。我是否错误地分割了数据?

在提取名字时出错。您正在使用:

string firstName = tmpString.substr(tmpString.find(" ") +1,tmpString.find(","));

第二个参数不正确。第二个参数是计数——要提取的字符数。它不是指结束位置。参考文档

将该行改为:

auto start = tmpString.find(" ") + 1;
auto end = tmpString.find(",");
string firstName = tmpString.substr(start, (end-start));

使用激励精神:

#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <iostream>
#include <string>
#include <vector>

int main(int argc, char** argv)
{
   std::string const str{"75428 Marston, Edward"};
   std::tuple<int, std::string, std::string> data;
   using namespace boost::spirit::x3;
   auto beg = std::begin(str), end(std::end(str));
   auto ret = parse(beg, end, int_ >> ' ' >> +~char_(',') >> ", " >> +char_ >> (eol | eoi), data);
   if(ret && (beg==end) )
    std::cout << "Parse done : " << std::get<0>(data) << " " << std::get<1>(data) << " " << std::get<2>(data) << "n";
    else
    std::cout << "Parse failed : '" << std::string(beg, std::next(beg, 5) ) << "'n";


    return 0;
}