在这部分代码中:
void inputData() {
Data temp;
std::cout << "Inserisci x\n";
std::cin >> temp.x;
fout << temp.x << "\n";
}
最后一行您有一个名为fout 的变量,该变量具有此函数的本地范围,该函数未在此代码块的任何位置或此范围内声明。您有两个选项来解决此问题,除非您在未指定的主函数之外的全局范围内声明此对象:
- 您可以在此函数中创建一个
std::ofstream 临时对象,但您必须open 和close 文件流。
- 或者您可以通过
reference 将ofstream object 传递给此函数。
我将分别展示一个示例:
void inputData() {
Data temp;
std::cout << "Iserisci x\n";
std::cin >> temp.x;
std::ofstream fout;
fout.open( /* filename & path */ );
fout << temp.x << "\n";
}
或者
void inputData( std::ostream& out ) {
Data temp;
std::cout << "Iserisci x\n";
std::cin >> temp.x;
out << temp.x << "\n";
}
然后在调用这个函数的代码块中你可以做...
{
//... some other code
std::ofstream fout;
fout.open( "path & filename", flags );
inputData( fout );
fout.close();
//... some other code
}
如果你仔细注意到这个函数,我传递了一个对 std::ostream 对象的引用,而不是 std::ofstream 对象。我为什么选择这样做?这很简单,因为这个函数现在可以接受任何输出流类型的对象,而不仅仅是一个输出文件流对象......
{
inputData( std::cout ); // will now print to console out
std::ostringsream ostr;
inputData( ostr ); // will now populate the output string stream object
// etc...
}
基本上把这行代码:fout << temp.x << "\n";在你的函数上面fout对象没有声明或定义在这个代码块的范围内,除非fout在main之外的全局命名空间中功能。
编辑 - 可选,但作为这行代码的附注:
fout.open("C:/Users/Shantykoff/Documents/visual studio 2017/Projects/Input_Output_fstream_basis/Input_Output_fstream_basis/Dats.txt",
std::ios::out | std::ios::app);
由于您使用的是 Visual Studio,我通常会这样做:
在解决方案资源管理器中的当前项目设置下:
- 在配置属性下 - 用于当前配置和平台设置
- 一般
- 输出目录:设置为 - $(SolutionDir)“ProjectName”\_build\
- 调试
- 工作目录:设置为 - $(ProjectDir)_build\
注意: "ProjectName" 只是项目实际名称的占位符。
那么这样你就不必从根目录C:\指定整个路径
然后在你的代码中当你有这样的文件时:
sample.txt - 放置在可执行文件现在所在的 _build 文件夹中,而不是“Visual Studio 的”默认位置。
1 2 3 4 5 6 7 8 9
main.cpp
int main() {
std::vector<unsigned> values;
std::ifstream in;
unsigned val;
in.open( "sample.txt" );
while ( in >> val ) {
values.push_back( val );
}
in.close();
// lets modify some values
for ( auto v : values ) {
v *= 10;
}
// Let's print new values to same file but lets append it to a new line
std::ofstream out;
out.open( "sample.txt", std::ios::app );
for ( auto v : values ) {
out << "\n";
out << v << " ";
}
out.close();
return 0;
}
sample.txt
1 2 3 4 5 6 7 8 9
10 20 30 40 50 60 70 80 90
现在,通过在解决方案资源管理器中创建 _build 文件夹,可以更轻松地读取长路径的代码,因为路径现在与项目目录相关,并且应该指向包含应用程序的同一文件夹可执行文件以及任何第三方依赖项 - 外部 dlls。现在就我自己而言,我选择在 build 文件夹名称的前面放置一个 underscore,只是为了将其保持在其父目录的 top 中。