如何从存储在任何其他结构中的文件中读取C ++中的数据,例如:.text文件

how to read data in c++ from a file stored in any other structure e-g: .text file

本文关键字:文件 数据 例如 text 读取 任何 其他 结构 存储      更新时间:2023-10-16

我必须从存储在计算机中的文本文件中读取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();
}

编辑:修复了事情并成功进行了测试。