c++ - 如何检测将文本文件读入int数组的新行
问题描述
101 175 123 52 78 184 202 8 219 15 49 254 86 62
156 213 41 200 123 131 252 186 108 116 39 205 243 120
218 239 201 109 52 173 244 58 185 18 64 209 165 222
81 136 247 149 183 206 164 214 179 121 176 200 89 128
我正在将数字文本文件读入动态分配的整数数组。我不确定如何在将数字读入 int 数据类型“while(num!='\n')”时检测换行符这是我迄今为止尝试过的。虽然我知道我们无法将字符读入 int 数据类型变量,但我不确定如何解决这个问题
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int num=0;
int size=0;
int* ptr=nullptr;
ifstream fin;
fin.open("numbers.txt");
while(fin>>num)
{
while(num!='\n')
{
int* nptr=new int[size+1];
for(int i=0; i<size; i++)
{
nptr[i]=ptr[i];
}
nptr[size++]=num;
ptr=nptr;
delete[] nptr;
nptr=nullptr;
fin>>num;
}
}
for(int i=0; i<size; i++)
{
cout<<ptr[i]<<endl;
}
}
解决方案
一种常见的方法是逐行读取文件,然后使用 istringstream 解析单行。
此外,当您使用 C++ 时,std::vector 比指向指针的容易出错的指针更适合此目的。
示例如下所示:
ifstream fin;
fin.open("numbers.txt");
std::string line;
std::vector<std::vector<int>> mat; // use vector of vector instead of pointer to pointer
while (std::getline(fin, line)) // read line-by-line
{
cout << line << "\n";
std::istringstream iss(line); // then process each line separately
int x;
std::vector<int> row;
while (iss >> x)
{
cout << x << '\t';
row.push_back(x);
}
mat.push_back(row);
cout << '\n';
}
// Check the output content
for( const auto &row : mat )
{
for( const auto &x : row )
{
cout << x << '\t';
}
cout << '\n';
}
推荐阅读
- github - 如何在 Github markdown 中折叠内容?
- c# - 基类的构造函数在 C# 中不被继承
- python-3.x - 将割线方法编程到 Python 中
- postgresql - 如何防止批量行删除操作?
- video-streaming - 如何在给定分段 MP4 文件的情况下生成 DASH 清单文件(MPD 文件)
- javascript - Javascript - 模拟点击 div 元素
- c++ - 为什么 SDL 窗口会立即关闭?
- firebase - Firestore 是否对不返回数据的读取收费
- android - 将 CharSequence 与 String 进行比较时出现不一致
- r - 尝试添加换行符以使其正常工作,但无法使其正常工作