c++ - C++ 文件逐行读取
问题描述
我正在尝试逐行读取文件。我的文件有点像这样:
一个 4 558 5
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];
的第 1 个字符line
分配给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];
}
推荐阅读
- android - Android/Kotlin - 将 TextInputLayout.END_ICON_CLEAR_TEXT 添加到 textview 不会执行 setOnFocusChangeListener
- android-studio - 图像减慢应用程序
- database - 删除弹性搜索快照
- r - R readr read_csv 跳过错误与 VROOM_CONNECTION_SIZE
- dialogflow-es - 从 webhook Actions Google 或 Google Assistant 中的 DialogFlow 启动 URL
- c# - 为不同的 EF 对象分解 Linq Where 子句
- html - 每当文本换行使 flex-box 缩小并删除间距时
- mysql - 查询以从不同列中选择日期范围
- javascript - 如何使用firebase查询唯一对?
- javascript - 获取 webpack 输出文件列表并在 PWA 的另一个模块中使用