如何从存储在任何其他结构中的文件中读取C ++中的数据,例如:.text文件
how to read data in c++ from a file stored in any other structure e-g: .text file
我必须从存储在计算机中的文本文件中读取C ++中的数据然后在空格的基础上标记数据,使每个单词成为单独的字符串
我尝试过代码,但它没有打印任何内容作为输出而不是黑色空白屏幕
// basic file operations
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
//using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");``
myfile << "Writing this to a file.n";
// myfile.close();`
getch();
return 0;
}
请帮忙:(
您发布的代码不会尝试将任何内容写入标准输出 ( std::cout
)。 它打开一个文件(例如.txt)并在其中写入"正在将此写入文件",关闭该文件,然后等待您按下按钮,然后再退出程序。 您看不到任何输出,因为您没有提供任何输出操作,也没有尝试从文件中读取任何内容。
首先使用 ifstream,因为您希望此文件作为输入而不是输出
其次,您发布的此代码与问题有什么关系?
试试这个:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("example.txt");
if (file.is_open())
{
std::string str;
while (std::getline(file, token, ' '))
{
//here str is your tokenized string
}
} else
{
std::cout << "Unable to open file";
}
}
getline 将获取下一个字符串,直到满足行尾或 ' '
此代码写入文件...也许有一种C++方法可以做到这一点,但 Strtok 会按照您的描述进行操作。
在
谷歌搜索:)的一分钟内找到
using namespace std;
string STRING;
ifstream myReadFile;
myReadFile.open("Test.txt");
char output[100];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
getline(myReadFile,STRING);
cout << STRING;
}
myReadFile.close();
}
编辑:修复了事情并成功进行了测试。
相关文章:
- 从 bmp 文件数据创建 MFC CBitmap
- 从存储为 Windows 资源 (c++) 的 png 中获取 png 文件数据
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 获取文件数据预处理器宏
- 错误的值是使用c++从CSV文件数据写入数组
- 无法在可视C++中检索资源文件数据
- 将文本文件数据读入字符数组时提取运算符的歧义
- 如何使用curl c ++源代码发布wav文件数据,如何使用c ++使用--data-binary?
- 如何在C++中读取 UTF-8 文件数据
- 如何在结构中存储二进制文件数据
- 无法从 turbo c 程序中的文件检索文件数据
- 使用 fstream 将文件数据从当前位置保存到文件末尾
- 通过Google Protobuf发送二进制文件数据
- 在通过套接字向服务器发送文件数据时,我得到了一些垃圾值?为什么
- 如何使用dlang读取二进制文件数据
- 程序使用FSCANF读取文件数据后崩溃
- 检测二进制文件数据的端性
- C++ 从文本文件数据类型读取为结构,并将数据存储在列表的向量中
- 将 FFT 应用于 WAV 文件数据的 C++
- C++内存映射的文件数据预取