文本文件如下所示:
3
String
String2
String3
我必须创建一个函数来从文本文件中读取所有字符串,将它们保存到数组中,然后在主函数中显示它。例如
void reading(int & count, string strings[]) {
ifstream fd "text.txt";
fd >> count;
for (int i=0; i<count; i++)
fd >> strings[i];
fd.close();
主要功能:
int main() {
int count=0;
string strings[100];
reading(count, strings);
for (int i=0; i<count; i++)
cout << strings[i] << endl;
字符串数写在文本文件的第一行。我怎样才能创建一个恰好是那个数字的数组?我需要它能够在主要/其他功能中访问它。(例如,用于写入另一个文本文件的功能)。
如果有非常重要的原因要对数组执行此操作,请使用std :: new,如下所示:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int reading(string** str_array, int& size, string filename) {
ifstream infile(filename.c_str());
if(!infile) {
cerr << "Unable to access file!\n";
return -1;
}
int n = 0;
infile >> size;
try{
*str_array = new string[size];
string str;
for (; n < size && infile; ++n) {
infile >> str;
(*str_array)[n] = str;
}
if (n != size)
cerr << "ERROR, read less than " << size << " strings!!\n\n";
} catch(bad_alloc& exc) {
return -2;
}
return 0;
}
int main() {
string* str_array = NULL;
int size;
if(reading(&str_array, size, "test.txt")) {
cerr << "Din't read file, exiting...\n";
return -1;
}
for(int i = 0; i < size; ++i)
cout << str_array[i] << endl;
delete [] str_array; // DO NOT FORGET TO FREE YOUR MEMORY
str_array = NULL;
return 0;
}
输出:
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3
但是,您在c ++中,没有为此使用std :: vector吗?
看看这有多简单:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int reading(vector<string>& v, string filename) {
ifstream infile(filename.c_str());
if(!infile) {
cerr << "Unable to access file!\n";
return -1;
}
int N = -1, n = 0;
infile >> N;
string str;
for (; n < N && infile; ++n) {
infile >> str;
v.push_back(str);
}
if (n != N)
cerr << "ERROR, read less than " << N << " strings!!\n\n";
return 0;
}
int main() {
vector<string> v;
if(reading(v, "test.txt")) {
cerr << "Din't read file, exiting...\n";
return -1;
}
for(size_t i = 0; i < v.size(); ++i)
cout << v[i] << "\n";
return 0;
}
输出:
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3
编辑:
我们必须传递一个指向我们要修改的内容的指针(即string*
),否则我们应用的更改将不会发生。自己对其进行测试,string*
而不是将a作为参数传递string**
,修改函数的主体,然后会发生什么。
要想出这个主意,想象一下我们想向指针写入新地址,该地址new
给了我们并保存了所请求的内存。我们确实在该函数中写入了该地址,但是当函数终止时,我们希望更改是持久的。以我的C语言函数为例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句