如何在c++中分割一行并从中提取值
How do I split a line and extract values from it in C++?
我在编写程序的一部分时遇到了麻烦,该程序将从文件中读取一个名称和10个数字。数据文件的结构是:
Number One
99 99 99 99 99 99 99 99 99 99
John Doe
90 99 98 89 87 90.2 87 99 89.3 91
Clark Bar
67 77 65 65.5 66 72 78 62 61 66
Scooby Doo
78 80 77 78 73 74 75 75 76.2 69
这是我所有的函数来获取数据,我甚至不确定这是否正确。
void input (float& test1, float& test2, float& test3, float& test4, float& test5, float& test6, float& test7, float& test8, float& test9, float& test10, string& studentname)
{
ifstream infile;
infile.open ("grades.dat");
if (infile.fail())
{
cout << "Could not open file, please make sure it is named correctly (grades.dat)" << "n" << "and that it is in the correct spot. (The same directory as this program." << "n";
exit(0);
}
getline (infile, studentname);
return;
}
使用标准c++习惯用法,一次读取两行(如果不可能,则失败):
#include <fstream>
#include <sstream>
#include <string>
#include <iterator> // only for note #1
#include <vector> // -- || --
int main()
{
std::ifstream infile("thefile.txt");
std::string name, grade_line;
while (std::getline(infile, name) && std::getline(infile, grade_line))
{
std::istringstream iss(grade_line);
// See #1; otherwise:
double d;
while (iss >> d)
{
// process grade
}
}
}
注意:如果内循环(标记为#1
)的唯一目的是存储所有分数,那么正如@Rob建议的那样,您可以使用流迭代器:
std::vector<double> grades (std::istream_iterator<double>(iss),
std::istream_iterator<double>());
流迭代器与上面的内部while
循环做同样的事情,即迭代double
类型的令牌。您可能希望将整个向量插入到一个大容器中,该容器包含名称和等级对std::pair<std::string, std::vector<double>>
。
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 如何从 std::atomic 中提取指针 T<T>?
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么istream不支持右值提取
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何设置一个范围来提取我想要获得的信息
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 视觉工作室项目.提取源文件夹名称
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 如何从一行 C++ 中提取两个字符串
- 是否可以使用一行代码从 std::cin 中提取格式化输入
- 每隔一行或每一列提取一个特征矩阵作为一个新矩阵
- 如何从一行中提取一个字符并将其放入常量字符*中
- 如何在c++中分割一行并从中提取值
- 使用正则表达式从C++中的一行文本中提取数据