如何将txt文件中的记录扫描到函数中的动态数组中 [英] How can I scan records from txt file into dynamic array in function
问题描述
我需要一个能够扫描文本文件中的记录并将它们存储到动态分配数组中的函数,我需要在其他函数中使用该数组。
稍后我需要访问某些行。
我有这样的文本文件:
record1.1
record1.2
record1.3
record2.1
record2.2
record2.3
等等,这些街区之间总是有空行..
我会很感激细节解释因为我是初学者。
我尝试过的事情:
我是这样做的,但我不喜欢我不知道如何将创建的数组存储在函数中以便在另一个函数中使用。
Arr [j] =(char *)malloc(10 *的sizeof(char)的);
fscanf(fr,%s,Arr [j]);
您还用C ++
标记了您的问题,所以你在这里:
#include < vector >
#include < string >
#include < algorithm > ;
#include < ; iostream >
#include < iterator >
使用 < span class =code-keyword> namespace std;
int main()
{
/ / 将字符串存储到向量
vector< string>字;
copy(istream_iterator< string>(cin),istream_iterator< string>(),back_inserter(word));
// 报告矢量内容
for ( const auto & w:word)
cout<< w<< ENDL;
}
程序期望输入来自stdin
(用你的输入文件提供它,你可以使用<
运算符进行输入重定向。)
对于此类任务,标准库类向量是最佳解决方案。在这里,您可以找到有关矢量的文档以及一些示例。如果您有固定大小,则可以使用阵列。 />
提示:尝试一些示例代码并在Youtube上观看一些视频用于学习。 ; - )
I need a function that will scan records in text file and store them into dynamicaly allocated array and i need use that array in others functions.
I need an access to some lines later on.
I have text file like this:
record1.1 record1.2 record1.3 record2.1 record2.2 record2.3
And so on, there is always an empty line between those blocks..
I would appreciate detail explanation because I'm beginner.
What I have tried:
I was doing it this way but i don't know how to store the created array in function to use in another.
Arr[j] = (char*)malloc(10*sizeof(char)); fscanf (fr, "%s", Arr[j]);
You tagged your question also withC++
, so here you are:
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <iterator> using namespace std; int main() { // store the strings into the vector vector<string> word; copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(word)); // report the vector content for (const auto & w : word) cout << w << endl; }
The program expects input fromstdin
(to feed it with you input file, you may use the<
operator for input redirection).
For such tasks is the standard library class vector the best solution. Here you find a documentation about vectors with some samples. If you have a fixed size you can use arrays.
Tip: try some sample code and watch some videos on Youtube for learning. ;-)
这篇关于如何将txt文件中的记录扫描到函数中的动态数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!