我尝试做的是在使用sstream库解析时从每行的文本文件中读取。我让程序运行但是它陷入了循环。
程序:
<firebase-document path="/build the path here" data="data" ></firebase-document>
<div class="card">
<h1>{{data.title}}</h1>
<paper-input label="item" value="{{data.item}}"></paper-input>
</div>
的test.txt:
string date;
int time;
float amount;
ifstream testFile("test.txt");
string token;
string line;
while(!testFile.eof()) {
while(getline(testFile,token,',')){
line += token + ' ';
}
stringstream ss(line);
ss >> date;
ss >> time;
ss >> amount;
cout << "Date: " << date << " ";
cout << "Time: " << time << " ";
cout << "Amount: " << amount << " ";
cout<<endl;
ss.clear();
}
testFile.close();
通缉输出:
10/12/1993,0800,7.97
11/12/1993,0800,8.97
我该如何有效地制作这个?
答案 0 :(得分:0)
不要使用eof
循环。 Why is iostream::eof inside a loop condition considered wrong?
逐行读取文件。 Read file line by line
使用,
作为分隔符拆分每一行的字符串。 Split a string in C++?
创建第二个和第三个字符串的std::stringstream
个对象,并使用operator>>
从中获取int
和double
个值。
答案 1 :(得分:0)
<div class="container">
<div class="row">
<!--<div class="col-sm-6"><img src="images/test.png"></div><div class="col-sm-6"><span class="pull-center"><img src="images/test.png"></span></div>-->
<div class="col-sm-12">
<nav class="col-sm-3" id="myScrollspy">
<ul class="nav nav-pills nav-stacked">
<li><a href="#account_register">account_register</a></li>
<li><a href="#login_logout">login_logout</a></li>
<li><a href="#buying_process">buying_process</a></li>
</ul>
</ul>
</li>
</ul>
</nav>
<div class="col-sm-9">
<div id="account_register">
<h1>buying_process</h1>
<p>Try to scroll this section and look at the navigation list while scrolling!</p>
</div>
<div id="login_logout"> <hr>
<h1>login_logout</h1>
<p>Try to scroll this section and look at the navigation list while scrolling!</p>
</div>
<div id="buying_process"> <hr>
<h1>buying_process</h1>
<p>Try to scroll this section and look at the navigation list while scrolling!</p>
</div>
</div>
您应该使用#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ifstream testFile("testdates.txt");
string line;
while(getline(testFile, line)){
string date;
int time;
float amount;
std::replace(line.begin(), line.end(), ',', ' ');
stringstream ss(line);
ss >> date;
ss >> time;
ss >> amount;
cout << "Date: " << date << " ";
cout << "Time: " << std::setfill('0') << std::setw(4) << time << " ";
cout << "Amount: " << amount << " ";
cout << '\n';
}
}
逐行阅读。您应该检查此返回值以了解何时退出(不是getline
)。然后,您可以用空格替换所有逗号,并使用现有的流解析代码来读取值。
请注意!eof
和ss.clear()
不是必需的,因为每次迭代都会重新创建testFile.close()
,并且在其析构函数中关闭ss
。