c++中find()命令的问题
Problems with find() command in c++
我试图拔出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;
}
相关文章:
- 初学者问题:如何使用这些晦涩难懂的命令,例如C++中的'RenderWindow'
- 在 C++ 中使用逗号的 echo 命令中存在问题
- 在 C++ Consol 中的数组中执行用户命令时出现问题
- g++ 命令 synatx 有什么问题?
- 通过命令行参数获取llvm ir文件时面临问题
- exteranl原生构建问题,构建命令失败,android工作室
- build命令失败,外部原生问题android工作室
- 从命令行获取参数时出现问题
- 修复了安装 OSRM 时使用"make"命令时的构建问题
- 从C 程序传递命令到终端的问题
- 在程序中获取 Linux 'dd' 命令的输出时遇到问题C++
- SFML loadFromFile命令的问题
- MVC:命令行应用程序的实现问题
- 从c++应用程序向bash传递源命令时出现问题
- 命令行参数问题
- Windows 上C++命令行参数的问题
- 图像处理(OpenCV with PHP) - exec 命令出现问题
- C++编译器问题:3>cl:命令行错误 D8016:'/clr'和'/arch:SSE2'命令行选项不兼容
- 执行命令行管理程序命令时出现性能问题
- 我在让非常基本的命令提示符文本处理器工作时遇到问题。ofstream() 的问题