我正在做一个fstream克隆,这应该是更简单的使用。我有多个“写”函数来写入文件,但是,这些版本在最后添加了一个新行,因此为了找到消除最后一行空白的方法,我创建了一个write_test函数来找到一种编写方法,而不添加最后一个空行。
很简单。
从理论上讲,这应该是可行的。但是,我不能迭代字符串数组,因为我无法得到它的大小。
我尝试了sizeof(lines)/sizeof(std::string)和sizeof(lines)/sizeof(lines[0]),都返回了相同的结果,0。
我的目标是获得字符串数组的实际大小,这样函数就可以迭代它。
这是我的main.cpp文件,
#include "bstdlib/fstream-new.hpp"
int main(){
// make object
bstd::fstream::file fs("./output/file.txt");
// string array
std::string str1, str2, str3;
str1="hello";
str2="world";
str3="!!!!!";
std::string strs[]={str1, str2, str3};
// write it, this is where the cactus on my seat lies
fs.write_test(strs);
}这是write_test函数
void write_test (std::string lines...) {
// make fstream object
std::fstream fs(this->fp.c_str(), std::fstream::out);
// get size of array
int range = sizeof(lines) / sizeof(lines[0]);
std::cout << range; // print
// make 1 grand string of each line
std::string grand_string;
for (int i=0; i<range-2; i++) {
grand_string += (lines[i]+"\n");
}
grand_string += lines[range-1];
// write, i used .c_str() because i felt as though that was what type it takes
fs << grand_string.c_str();
fs.close();
this->scan(); // just a function to read the file and update this->lines, irrelevant to the problem
}它打印字符串数组的大小为0。当然,它没有将任何内容写入文件,而是将其保留为空白。
发布于 2022-09-15 03:39:22
如果您想在函数strs中遍历整个write_test数组,那么函数write_test必须知道以下内容:
在您发布的代码中,函数main给函数write_test一个指向数组开始的指针,但它没有提供任何关于数组大小或结束的信息。因此,函数write_test不可能遍历整个数组。
线
fs.write_test(strs);在函数中,main不会将实际的数组strs传递给函数write_test。相反,表达式strs将decay到&strs[0],即它将衰减到指向数组的第一个元素的指针。因此,不向函数write_test传递有关数组大小的信息。
但是,您可以将数组的大小作为单独的参数传递:
fs.write_test( strs, sizeof strs / sizeof *strs );要使此操作正常,您必须将函数write_test的签名更改为以下内容:
void write_test( std::string lines[], size_t length )另一种更好的选择是使用std::vector,因为这种类型的对象在传递给函数时不会衰减到指针。因此,所有关于std::vector长度的信息都将被保留,被调用的函数可以很容易地访问。
为了创建std::vector并将其传递给函数write_test,可以使用以下代码:
#include <iostream>
#include <string>
#include <vector>
#include "bstdlib/fstream-new.hpp"
int main() {
// make object
bstd::fstream::file fs("./output/file.txt");
// string array
std::string str1, str2, str3;
str1="hello";
str2="world";
str3="!!!!!";
std::vector<std::string> strs{ str1, str2, str3 };
fs.write_test( strs );
}要做到这一点,必须将write_test的签名更改为:
void write_test( std::vector<std::string> &lines )https://stackoverflow.com/questions/73725161
复制相似问题