读取直到某些字符使用for循环

时间:2013-11-02 03:00:12

标签: c++

如何使用substr函数读取第一列值(name,name2和name3)?

name;adress;item;others;
name2;adress;item;others;
name3;adress;item;others;

我写过

  cout << "Read data.." << endl;
    if (dataFile.is_open()) {
        i=-1;
        while (dataFile.good()) {
            getline (dataFile, line);
            if (i>=0) patient[i] = line;
            i++;
        }
        dataFile.close();
    }

3 个答案:

答案 0 :(得分:0)

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

int main()
{
    std::fstream f("file.txt");
    if(f)
    {
        std::string line;
        std::vector<std::string> names;
        while(std::getline(f, line))
        {
            size_t pos = line.find(';');
            if(pos != std::string::npos)
            {
                names.push_back(line.substr(0, pos));
            }
        }

        for(size_t i = 0; i < names.size(); ++i)
        {
            std::cout << names[i] << "\n";
        }
    }

    return 0;
}

答案 1 :(得分:0)

像这样:

int pos = s.find(';');
if (pos == string::npos) ... // Do something here - ';' is not found
string res = s.substr(0, pos);

您需要找到第一个';'的位置,然后从零开始substr到该位置。这是demo on ideone

答案 2 :(得分:0)

在读取第一个分号之前的内容之后,您可以忽略该行的其余部分:

std::vector<std::string> patient;

std::string line;
while (std::getline(file, line, ';'))
{
    patient.push_back(line);
    file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
相关问题