读取直到使用 for 循环的特定字符
read until certain character using for loop
如何使用substr函数读取第一列值(名称,名称2和名称3)?
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();
}
#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;
}
像这样:
int pos = s.find(';');
if (pos == string::npos) ... // Do something here - ';' is not found
string res = s.substr(0, pos);
你需要找到第一个';'
的位置,然后把substr
从零带到那个位置。这是关于 ideone 的演示。
在读取第一个分号之前的内容后,您可以忽略该行的其余部分:
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'); }
相关文章: