c++ std::fstream。如何读取行开头的数字(浮点数或整数),然后跳到下一个?使用命名变量,因此没有循环
我有一个以下格式的文本文件:
100 #gravity
5000 #power
30 #fulcrum
我想将这些值分配给命名变量,如下所示:
void Game::reloadAttributes()
{
float test1, test2, test3;
string line;
std::fstream file;
file.open("attribs.txt");
if (file.is_open()) {
cin >> test1;
file.ignore(50, '\n');
cin >> test2;
file.ignore(50, '\n');
cin >> test3;
file.ignore(50, '\n');
file.close();
}
else
{
cout << "\n****Couldn't open file!!****\n" << endl;
}
cout << ">>>> " << test1 << ", " << test2 << ", " << test3 << endl;
}
当然,这些值不是指定给本地测试变量的,而是在属于 Game 类的字段中,只需使用它们测试其读数是否正确。程序只是挂在 cin >>测试1。我之前尝试过使用 getLine(file, line) ,但没有成功。我做错了什么?干杯
I have a text file in the following format:
100 #gravity
5000 #power
30 #fulcrum
I want to assign these values to named variables, like so:
void Game::reloadAttributes()
{
float test1, test2, test3;
string line;
std::fstream file;
file.open("attribs.txt");
if (file.is_open()) {
cin >> test1;
file.ignore(50, '\n');
cin >> test2;
file.ignore(50, '\n');
cin >> test3;
file.ignore(50, '\n');
file.close();
}
else
{
cout << "\n****Couldn't open file!!****\n" << endl;
}
cout << ">>>> " << test1 << ", " << test2 << ", " << test3 << endl;
}
Of course, these aren't destined for the local test variables, but in fields belonging to the Game class, just using these to test its reading correctly. The program just hangs at cin >> test1. Ive tried using getLine(file, line) just beforehand, that didnt work. What am I doing wrong? Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用
cin
而不是file
作为输入行。而不是
cin >> test1;
,执行文件>>测试1;
。那么它应该可以正常工作。You're using
cin
instead offile
for your input lines.Instead of
cin >> test1;
, dofile >> test1;
. Then it should work fine.istream
类型的对象(在本例中为cin
)接受用户输入。因此,程序当然会等待您输入一个值,然后将其分别存储在test1
、test2
和test3
中。要解决您的问题,只需将
cin
替换为file
即可:输出:
An object of type
istream
(in this casecin
) takes user input. So of course the program will wait for you to input a value and then store it insidetest1
,test2
, andtest3
respectively.To fix your issue, just replace
cin
withfile
as such:Output: