我正在尝试取出firstName字符串,但是我得到了非常奇怪的输出。
示例数据: 75428马斯顿,爱德华
通缉输出: 马斯顿爱德华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 textFile\nPlease make sure the file is in the same folder as the .cpp program" << endl;
printData(implementData);
return 0;
不仅仅是这一个数据,First Name的所有数据似乎都停在第13个字符而不是停在逗号处。我错误地拆分了数据吗?
答案 0 :(得分:1)
使用助推精神:
{{1}}
答案 1 :(得分:1)
提取名字时出错。您正在使用:
string firstName = tmpString.substr(tmpString.find(" ") +1,tmpString.find(","));
第二个论点不正确。第二个参数是计数 - 要提取的字符数。它并不意味着最终立场。请参阅the documentation。
将该行更改为:
auto start = tmpString.find(" ") + 1;
auto end = tmpString.find(",");
string firstName = tmpString.substr(start, (end-start));