C++逐行读取文件
C++ File Reading Line by Line
我正在尝试逐行读取文件。我的文件有点像这样:
A 4 558 5
A 123 145 782
x 47 45 789
如果第一个字符是 a,我想将它前面的三个值存储在一个数组中。我正在尝试这个,但它似乎不起作用:
while (std::getline(newfile, line))
{
if (line[0] == 'a')
{
vertex[0] = line[1];
vertex[1] = line[2];
vertex[2] = line[3];
//vertices.push_back(vertex);
}
我正在尝试这个,但它似乎不起作用:
当您使用
vertex[0] = line[1];
line
的第 1 个字符分配给vertex[0]
。这不是你的意图。您希望将行中a
后的第一个数字分配给vertex[0]
。
您可以使用std::istringstream
提取数字。
if (line[0] == 'a')
{
// Make sure to ignore the the first character of the line when
// constructing the istringstream object.
std::istringstream str(&line[1]);
str >> vertex[0] >> vertex[1] >> vertex[2];
}
这段代码包含了对这一点的建议和答案。
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::ifstream newfile("vals");
if (!newfile)
std::cout << "Exiting...n";
std::string line;
int vertex[3][3];
int i = 0;
while(std::getline(newfile, line)) {
if (line.empty()) continue;
if (line[0] == 'a') {
// Make sure to ignore the the first character of the line when
// constructing the istringstream object.
std::istringstream str(&line[1]);
str >> vertex[i][0] >> vertex[i][1] >> vertex[i][2];
}
++i;
}
newfile.close();
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
std::cout << vertex[j][k] << ' ';
}
std::cout << 'n';
}
}
问题是变量line
是一个std::string
,在字符串上使用[n]
会得到字符和索引n,并且你正在尝试获取第n个单词。
另一种方法(为了学习,上面的代码使用首选方法)是自己手动提取数字。
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::ifstream newfile("vals");
if (!newfile)
std::cout << "Exiting...n";
std::string line;
int vertex[3][3];
int i = 0;
while(std::getline(newfile, line)) {
if (line.empty()) continue;
if (line[0] == 'a') {
line = line.substr(2);
int j = 0;
std::string::size_type loc;
do {
loc = line.find_first_of(" ");
std::string tmp = line.substr(0, loc);
vertex[i][j] = std::stoi(tmp);
line = line.substr(loc + 1);
++j;
} while(loc != std::string::npos);
}
++i;
}
newfile.close();
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
std::cout << vertex[j][k] << ' ';
}
std::cout << 'n';
}
}
应该很清楚为什么首选字符串流方法。此方法手动切行并手动将提取的数字(仍存储为字符串)转换为存储在数组中的int
。同时,上述方法对您隐藏了许多肮脏的工作,并且也非常有效地完成了工作。虽然我可能不必在第二个示例中继续修剪变量line
(但我需要另一个变量),但我的反驳是我根本不会首先选择这条路线。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量