0

現在、

私はこの文字列を持っていますus,muscoy,Muscoy,CA,,34.1541667,-117.3433333

US と CA を解析する必要があります。これにより、USを正しく解析できました。

std::string line;
std::ifstream myfile ("/Users/settingj/Documents/Country-State Parse/worldcitiespop.txt");    
while( std::getline( myfile, line ) )
{

    while ( myfile.good() )
    {
        getline (myfile,line);
        //std::cout << line << std::endl;

        std::cout << "Country:";
        for (int i = 0; i < 2/*line.length()*/; i++)
        {
            std::cout << line[i];
        }
    }

}

しかし、CA への解析に問題があります。

文字列内の「,」の出現数を見つけるために掘り下げたコードをいくつか紹介しますが、「この文字列を 3 番目と 4 番目の ',' の出現の間で解析するという問題があります。

 // Counts the number of ',' occurrences
 size_t n = std::count(line.begin(), line.end(), ',');
 std::cout << n << std::endl;
4

3 に答える 3

2

この目的のために、boost::split関数 (または) を使用できます。boost::tokenizer文字列を に分割しますvector<string>

std::string line;
std::vector<std::string> results;
boost::split(results, line, boost::is_any_of(","));
std::string state = results[3];
于 2013-07-29T18:49:46.993 に答える
1

これは STL バージョンで、シンプルなカンマ区切りの入力ファイルに適しています。

#include<fstream>
#include <string>
#include <iostream>
#include<vector>
#include<sstream>

std::vector<std::string> getValues(std::istream& str)
{
    std::vector<std::string>   result;
    std::string   line;
    std::getline(str,line);

    std::stringstream   lineS(line);
    std::string   cell;

    while(std::getline(lineS,cell,','))
        result.push_back(cell);

    return result;
}


int main()
{
    std::ifstream f("input.txt");
    std::string s;

   //Create a vector or vector of strings for rows and columns

   std::vector< std::vector<std::string> > v; 

   while(!f.eof())
      v.push_back(getValues(f));

   for (auto i:v)
   {  
      for(auto j:i)
         std::cout<<j<< " ";
      std::cout<<std::endl;
   }
}
于 2013-07-29T19:19:46.840 に答える
1

授業じゃなくて……はは……授業の質問みたいだけど……

私は解決策を持っています:

        int count = 0;
        for (int i = 0; i < line.length(); i++)
        {
            if (line[i] == ',')
                count++;
            if (count == 3){
                std::cout << line[i+1];
                if (line[i+1] == ',')
                    break;
            }
        }

もっと考えなければならなかった :P

于 2013-07-29T19:00:22.320 に答える