0

我有一个将信息输出到类中的文件。具体来说,我试图输出的字符串之一将进入一个向量。问题是我试图采用一个字符串(在这种情况下),它将被格式化:

interest_string = "food, exercise, stuff"

所以基本上我想把上面的字符串变成一个数组字符串,或者以某种方式将上面的字符串复制到由逗号分隔符分隔的每个单独字符串中的向量中。

void Client::readClients() {
    string line;


    while (getline( this->clients, line ))
    {

        string interest_num_string, interest_string;

        istringstream clients( line );
        getline( clients, this->sex, ' ' );
        getline( clients, this->name, ',' );
        getline( clients, this->phone, ' ' );
        getline( clients, interest_num_string, ' ' );
        getline( clients, interest_string, '.' );

        this->interests = atoi(interest_num_string.c_str());

        cout << this->sex << "\n" << this->name << "\n" << this->phone << "\n" << interest_num_string << "\n" << interest_string;
    }

    this->clients.close();
}
4

3 回答 3

2

getline提示: is的替代签名

istream& getline ( istream& is, string& str, char delim );

strtok在 C 中也是一个可行的选择,它对低级字符串操作不太残酷。

于 2012-06-11T01:25:30.187 回答
0

您可以使用矢量或其他合适的容器。您将需要创建一个“人”类,该类将包含您读入并放入容器中的所有数据。

void Client::readClients(std::vector<MyClass*>& myPeople)
{
    //  ... other parts of your code

    // Create a person
    pointerToPerson = new Person();

    // read them in
    getline(clients, pointerToPerson->field, ' ');

    // After you load a person just add them to the vector
    myPeople.push_back(pointerToPerson);

    // more of your code ...
}
于 2012-06-11T01:51:33.140 回答
0

简单的 C++ 代码:

  string s = "abc,def,ghi";
  stringstream ss(s);
  string a,b,c;
  ss >> a ; ss.ignore() ; ss >> b ; ss.ignore() ; ss >> c;    
  cout << a << " " << b << " " << c << endl;

输出 :

abc def ghi

于 2013-05-27T14:25:53.837 回答