c++ - 从一个文件 c++ 中读取不同的变量类型
问题描述
我在将特定格式的数据读入不同的变量时遇到了一些麻烦。我需要从文件中读取数据并存储到 5 个不同变量类型的不同变量中。(字符串名称、字符串鱼、字符串位置、浮点长度、浮点重量)
我尝试存储的数据格式如下:
使用 getline() 函数从文件中获取名称、鱼和位置没有问题。我的问题是长度和宽度。
ifstream file("test.txt");
while(file.good())
{
getline(file, Name);
getline(file, Species);
getline(file, Location);
file >> Length;
file >> Weight;
cout << Name << "\n" << Species << "\n" <<Location << "\n" <<Length << "\n";
}
当我使用以下代码时,输出会变得不稳定,并且在第一次列出之后会乱序打印数据。对此的任何帮助将不胜感激。
解决方案
ifstream file("test.txt");
while (file) {
getline(file, Name);
getline(file, Species);
getline(file, Location);
file >> Length;
file >> Weight;
if (file) {
cout << Name << "\n" << Species << "\n" <<Location << "\n" <<Length << "\n";
// add this to skip the 2 newlines before reading the next string
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else {
throw "Invalid input";
}
}
推荐阅读
- sql - 使用 OPENJson 向表中插入数据
- embedding - 谷歌colab中gpu中的cuda内存不足问题
- c# - 没有 ID 为 1 的文件。文件列表可能已更改 Blazor
- rest - 我可以在同一台服务器上部署多个前端应用程序(网络/移动)和 1 个后端吗?
- postgis - pgAdmin 如何显示地理可视化?
- ios - 如何在objective-c上为这些textview设置自动高度
- json - 如何使用 Laravel Eloquent(POSTGRESQL)从 JSON 列中转换字段?
- python - 如何使用 for 循环制作字符串列表
- c# - Unity Serial.ReadLine() 问题
- spring - 在没有隐藏输入字段的 pojo 类中获取禁用的下拉值