无法使用 fstream 将值存储在文本文件中
not able to store value in text file using fstream
我是C ++编程的新手,我无法存储在文本文件中。这是一个非常简单的程序。我之前使用与我得到结果相同的方法存储值。
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ofstream fout("one.txt",ios::in);
int val1, rel1;
char val2[20], rel2[20];
cout<<" n enter the integer value";
cin>>val1;
cout<<" n enter the string value ";
cin>>val2;
fout.close();
ifstream fin("one.txt");
fin>>rel1;
fin>>rel2;
cout<<"the integer value .n"<<rel1;
cout<<"the string value .n"<<rel2;
fin.close();
if (fout==NULL) {
cout<<"the file is empty";
}
return 0;
}
输入100名字 荒谬的输出是整数值为 32760字符串值为 00Dv0
> 这里有许多假设似乎需要澄清。
- 如果要写入文件,则需要使用 fout <<rel1;
- 您(通常)不能像在 if(fout == NULL) 中那样将对象与 NULL 进行比较。这适用于 C# 和 Java,因为在这些语言中,所有对象实际上都是引用,C++中您可以指定何时需要对象以及何时需要引用。
- 您指定要使用 fout 从文件中读取而不是写入文件,即"ios::in"。
等待一些测试完成有点无聊,所以我写了我如何编写该程序:
#include<iostream>
#include <string>
#include<fstream>
int main() {
std::ofstream fout("one.txt",std::ios::out);
int val1, rel1;
std::string val2, rel2;
std::cout <<"enter the integer value: ";
std::cin >>val1;
std::cout <<"enter the string value: ";
std::cin >>val2;
fout <<val1 <<" " <<val2;
fout.close();
std::ifstream fin("one.txt", std::ios::in);
if(!fin.good()) {
std::cout <<"Failed to open filen";
return 1;
}
fin >>rel1;
fin >>rel2;
std::cout <<"the integer value: " <<rel1 <<"n";
std::cout <<"the string value: " <<rel2 <<"n";
fin.close();
return 0;
}
相关文章:
- 打印逐行存储的文本文件
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 是否保证相同内容字符串文本的存储相同?
- 从文本文件读取,然后将项目存储到列表中
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 如何将函数的输出数据存储在文本文件中
- 如何在不知道大小的情况下读取文本文件并存储到数组中
- 将文本文件中的文本存储到六个不同的矢量中(C++)
- 为什么使用 C++ 中的类对象写入文件中的数据以非文本格式存储?
- C++读取文本文件并存储数据
- 如何有效地读取和存储 1GB 文本文件中的数据
- 是否可以将来自 Win32 EDIT 控件的文本输入存储在C++ std::string 中?
- std::bad_alloc 将文本文件中的单个字符存储到矢量C++中时
- C ++将文本存储在数组的不同索引中,并带有一两个
- 在 c++ 中存储文本常量
- 最佳数据结构存储文本文件中的数字集
- 在C++中,使用什么数据结构来快速存储文本文件,该文件具有可变的行数和可变的子元素数
- 为文字处理器存储文本的更好方法是什么?