c++中的Getline问题
Getline Issue in C++
我有一个显示如下内容的文本文件:
John Smith 21 UK
David Jones 28 FRANCE
Peter Coleman 18 UK
和我试图剥离每个单独的元素到一个向量数组。我已经尝试使用一个制表符分隔符的getline函数,但它存储每个元素。例如:
getline (f, line, 't');
records.push_back(line);
如何逐行分隔?其思想是执行搜索并输出相应的行。例如,搜索Jones将打印出第二行。
这是我目前所拥有的,但正如你所看到的,它没有给我想要的结果:
string sString;
string line;
string tempLine;
string str;
vector<string> records;
cout << "Enter search value: " << endl;
cin >> sString;
cout << "nSEARCHINGnn";
ifstream f("dataFile.txt");
while (f)
{
while(getline (f, tempLine))
{
getline (f, line, 't');
records.push_back(line);
}
for(int i=0; i < records.size(); i++)
{
if(sString == records[i]) {
cout << "RECORD FOUND" << endl;
for(int j=0; j < records.size(); j++)
{
cout << j;
cout << records[j] << "t";
}
}
}
}
f.close();
第一个getline
从输入中提取完整的一行。第二个命令从下一行提取一个字段。如果你想要恢复分解为字段的行,您应该这样做:
std::vector<std::vector<std::string>> records;
std::string line;
while ( std::getline( f, line ) ) {
records.push_back( std::vector<std::string>() );
std::istringsream fieldParser( line );
std::string field;
while ( std::getline( fieldParser, field ) ) {
records.back().push_back( field );
}
}
这将产生一个记录向量,每个记录在其中一个场的向量。更常见的情况是,您希望使用结构体对于记录,并在行上做更多的解析,例如:
struct Field
{
std::string firstName;
std::string lastName;
int age;
std::string country;
};
std::vector<Field> records;
std::string line;
while ( std::getline( f, line ) ) {
std::istringsream fieldParser( line );
Field field;
fieldParser >> field.firstName >> field.lastName >> field.age >> field.country >> std::skipws;
if ( !fieldParser || fieldParser.get() != EOF ) {
// Error occurred...
} else {
records.push_back( field );
}
}
(只有当所有字段都不能工作时,这个简单的东西才会工作包含空白。但是扩展起来很简单)
你正在把getline
变成tempLine
,它吃掉了一整行,然后你在循环中也做了一个不同的getline。这就是为什么它不起作用的一个重要部分——你只是简单地扔掉了包含大量数据的tempLine
。
相关文章:
- 我在C++中使用 getline() 函数时遇到问题
- 使用getline读取.csv文件时出现问题
- 此C Getline函数的C 代码有什么问题
- 如何在 for 循环中解决潜在的 getline() 问题,数组的第一个索引没有显示?
- 使用getline的问题
- 找不到用户定义的 getline。自动扣款有问题?
- 我在使用 cin.getline() 从用户那里获取 3 个字符串并使用指针数组来存储它们时遇到问题
- C++将csv读取到向量中,getline()问题
- 有人能解释一下getline和char的问题吗
- 用弦乐库解析行时的std :: getline问题
- C++:ifstream getline 问题交叉编译到 OpenWRT 发行版中
- getline() 函数的问题
- 使用getline函数时出现问题
- 使用 getline() 的字符串输入问题
- 注意:(getline不是问题所在)C++getline()停止在用户定义的函数中工作,但在主函数中工作
- 使用 getline() 从文件中读取行时出现问题
- 关于getline(cin,string)的C++快速问题
- 涉及getline()和循环的C++问题
- 遇到getline、fstream、作用域不一致的问题
- Getline来自一个文件和另一个未知问题