C++逐行读取文件

C++ File Reading Line by Line

本文关键字:文件 读取 逐行 C++      更新时间:2023-10-16

我正在尝试逐行读取文件。我的文件有点像这样:

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(但我需要另一个变量),但我的反驳是我根本不会首先选择这条路线。