2016-08-31 3 views
-1

firstName文字列を取り出そうとしていますが、非常に奇妙な出力が出ています。Cでのfind()コマンドの問題

サンプルデータ: 75428マーストン、エドワード

募集出力: マーストンエドワード75428

出力受信: マーストン、EDWAエドワード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; 

にですこの1つのデータだけでなく、ファーストネームのすべてのデータがsto pをカンマで止めるのではなく、13番目の文字に置き換えます。データを間違って分割していますか?ブーストスピリットの

+0

使用この参照:に並ぶ

変更http://stackoverflow.com/questions/236129/split-a-string-in-c –

答えて

1

あなたが最初の名前を抽出する際にエラーが発生しています。

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

第2引数が正しくありません。 2番目の引数は、カウント(抽出する文字数)を意味します。それは最終的な位置を意味するものではありません。 the documentationを参照してください。あなたの文字列を分割する

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

用途:

#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; 
}