从文件中读取数据并将每行存储在数组中
Reading data from a file and storing each line in an array?
我有一个整数行文件。我想把每一行读入数组的一个槽中。我有下面的代码,但它不工作。我不确定我是否走对了路。
void Read_Save() {
ifstream in;
int arr[100];
string line;
in.open("file.txt");
while (in.peek() != EOF)
{
getline(in, line, 'n');
strcpy(arr, line.c_str());
}
in.clear(); in.close();
}
有几种方法可以从字符串中解析整数值。
首先,让我们修复你的循环:
int pos = 0;
while( std::getline(in, line) && pos < 100 )
{
int value = 0;
// Insert chosen parsing method here
arr[pos++] = value;
}
下面是一个非详尽的常用选项列表:
使用
std::strtol
// Will return 0 on error (indistinguishable from parsing actual 0) value = std::strtol( line.c_str(), nullptr, 10 );
使用
std::stoi
// Will throw exception on error value = std::stoi( line );
构建
std::istringstream
并从中读取:std::istringstream iss( line ); iss >> value; if( !iss ) { // Failed to parse value. }
使用
std::sscanf
if( 1 != std::sscanf( line.c_str(), "%d", &value ) ) { // Failed to parse value. }
现在,注意循环检查pos < 100
上的bounds-test。这是因为您的数组有存储限制。实际上,您还使用Read_Save
中的本地数组覆盖了全局数组,从而将其隐藏在一个较小的数组中,该数组将在函数结束时丢失。
可以使用标准库提供的其他容器类型拥有任意大小的"数组"(实际上不是数组)。提供随机访问的有用的是std::vector
和std::deque
。让我们使用矢量并更改Read_Save
的定义,使其更有用:
std::vector<int> Read_Save( std::istream & in )
{
std::vector<int> values;
std::string line;
for( int line_number = 1; getline( in, line ); line_number++ )
{
try {
int value = std::stoi( line );
values.push_back( value );
}
catch( std::bad_alloc & e )
{
std::cerr << "Error (line " << line_number << "): Out of memory!" << std::endl;
throw e;
}
catch( std::exception & e)
{
std::cerr << "Error (line " << line_number << "): " << e.what() << std::endl;
}
}
return values;
}
最后,调用变成:
std::ifstream in( "file.txt" );
std::vector<int> values = Read_Save( in );
不能使用strcpy()
将字符串转换为整数。您可以使用std::strtol()
或std::stoi()
,甚至std::istringstream
,例如:
int arr[1000];
void Read_Save() {
ifstream in;
string line;
in.open("file.txt");
int index = 0;
while ((index < 1000) && (getline(in, line)))
{
if (istringstream(line) >> arr[index])
++index;
}
}
在您的情况下最好是使用std::vector
。代码看起来像这样:
void Read_Save()
{
std::ifstream in("file.txt");
int value;
std::vector<int> arr;
while (in >> value)
arr.push_back(value);
for(int i(0); i < arr.size(); i++)
std::cout << arr[i] << ", ";
std::cout << std::endl;
in.close();
}
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组