问题描述
101 175 123 52 78 184 202 8 219 15 49 254 86 62
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
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
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
81 136 247 149 183 206 164 214 179 121 176 200 89 128
我正在将数字文本文件读取到动态分配的整数数组中.我不确定在将数字读入int数据类型"while(num!='\ n')"时如何检测换行符.尽管我知道我们无法将字符读入int数据类型变量中,但我不确定如何解决此问题
I am reading a numbers text file into a dynamically allocated integer array. I am not sure how to detect newline while reading numbers into int data type "while(num!='\n')" This is what I have tried ao far. Although I know we can't read characters into int data type variable but I ain't sure how to tackle this problem
#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解析一行.
A common approach is to read the file line-by-line, then use istringstream to parse a single line.
同样,当您使用C ++时,std :: vector比容易出错的指针更适合于此目的.
Also as you are using C++, std::vector would be much more suitable for this purpose than the error-prone pointer to pointer.
示例如下:
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';
}
这篇关于如何检测将文本文件读入int数组的换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!