从C ++文件中读取字符串 [英] Reading a string from a file in C++

查看:88
本文介绍了从C ++文件中读取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串直接存储到文件中以供以后在C ++中读取(基本上是为整个作用域,我正在尝试将具有字符串变量的对象数组存储在文件中,并且这些字符串变量将被完全读取类似于object [0] .string).但是,每次我尝试读取字符串变量时,系统都会给我一个混乱的错误.以下代码是我正在尝试的基本部分.

I'm trying to store strings directly into a file to be read later in C++ (basically for the full scope I'm trying to store an object array with string variables in a file, and those string variables will be read through something like object[0].string). However, everytime I try to read the string variables the system gives me a jumbled up error. The following codes are a basic part of what I'm trying.

#include <iostream>
#include <fstream>
using namespace std;

/*
//this is run first to create the file and store the string
int main(){
    string reed;
    reed = "sees";
    ofstream ofs("filrsee.txt", ios::out|ios::binary);
    ofs.write(reinterpret_cast<char*>(&reed), sizeof(reed));
    ofs.close();

}*/

//this is run after that to open the file and read the string
int main(){
    string ghhh;
    ifstream ifs("filrsee.txt", ios::in|ios::binary);
    ifs.read(reinterpret_cast<char*>(&ghhh), sizeof(ghhh));
    cout<<ghhh;
    ifs.close();
    return 0;
}

第二部分是我尝试阅读时遇到的麻烦.抱歉,如果以前有人问过,我已经环顾了类似的问题,但是其中大多数与我要尝试的内容有些不同,或者我不太了解他们想要做什么(仍然相当的新手.)

The second part is where things go haywire when I try to read it. Sorry if it's been asked before, I've taken a look around for similar questions but most of them are a bit different from what I'm trying to do or I don't really understand what they're trying to do (still quite new to this).

推荐答案

我在做什么错了?

您正在从文件中读取数据,并试图将数据放入字符串结构本身,然后将其覆盖,这是完全错误的.

What am I doing wrong?

You are reading from a file and trying to put the data in the string structure itself, overwriting it, which is plain wrong.

可以在 http://www.cplusplus.com/reference上进行验证/iostream/istream/read/,您使用的类型是错误的,并且您知道它是因为必须将 std :: string 强制为 char * 使用 reinterpret_cast .

As it can be verified at http://www.cplusplus.com/reference/iostream/istream/read/ , the types you used were wrong, and you know it because you had to force the std::string into a char * using a reinterpret_cast.

C ++提示:在C ++中使用 reinterpret_cast (几乎)总是表明您做错了事.

C++ Hint: using a reinterpret_cast in C++ is (almost) always a sign you did something wrong.

很久以前,读取文件很容易.在某些类似于Basic的语言中,您使用了 LOAD 函数,并使用了voilà!,您已经拥有了文件.那为什么我们现在不能做呢?

A long time ago, reading a file was easy. In some Basic-like language, you used the function LOAD, and voilà!, you had your file. So why can't we do it now?

因为您不知道文件中的内容.

  • 可能是字符串.
  • 这可能是结构的序列化数组,其中包含从内存中转储的原始数据.
  • 它甚至可以是实时流,即连续附加的文件(日志文件,stdin等).
  • 您可能想逐字读取数据
  • ...或逐行...
  • 或者文件太大,以致它不能容纳在字符串中,因此您希望按部分读取它.
  • 等.

更通用的解决方案是使用get函数(参见

The more generic solution is to read the file (thus, in C++, a fstream), byte per byte using the function get (see http://www.cplusplus.com/reference/iostream/istream/get/), and do yourself the operation to transform it into the type you expect, and stopping at EOF.

std :: isteam 界面具有您以不同方式读取文件所需的所有功能(请参见

The std::isteam interface have all the functions you need to read the file in different ways (see http://www.cplusplus.com/reference/iostream/istream/), and even then, there is an additional non-member function for the std::string to read a file until a delimiter is found (usually "\n", but it could be anything, see http://www.cplusplus.com/reference/string/getline/)

好,我明白了.

我们假设您在文件中放入的是 std :: string 的内容,但要使其与C样式字符串(即 \ 0 字符标记字符串的结尾(否则,我们将需要加载文件直到到达EOF).

We assume that what you put in the file is the content of a std::string, but keeping it compatible with a C-style string, that is, the \0 character marks the end of the string (if not, we would need to load the file until reaching the EOF).

我们假设您希望函数 loadFile 返回后完全加载整个文件内容.

And we assume you want the whole file content fully loaded once the function loadFile returns.

因此,这是 loadFile 函数:

#include <iostream>
#include <fstream>
#include <string>

bool loadFile(const std::string & p_name, std::string & p_content)
{
    // We create the file object, saying I want to read it
    std::fstream file(p_name.c_str(), std::fstream::in) ;

    // We verify if the file was successfully opened
    if(file.is_open())
    {
        // We use the standard getline function to read the file into
        // a std::string, stoping only at "\0"
        std::getline(file, p_content, '\0') ;

        // We return the success of the operation
        return ! file.bad() ;
    }

    // The file was not successfully opened, so returning false
    return false ;
}

如果您使用的是启用C ++ 11的编译器,则可以添加此重载函数,而无需花费任何费用(在C ++ 03中,对裸机进行优化,它可以使您失去了一个临时对象):

If you are using a C++11 enabled compiler, you can add this overloaded function, which will cost you nothing (while in C++03, baring optimizations, it could have cost you a temporary object):

std::string loadFile(const std::string & p_name)
{
    std::string content ;
    loadFile(p_name, content) ;
    return content ;
}

现在,出于完整性考虑,我编写了相应的 saveFile 函数:

Now, for completeness' sake, I wrote the corresponding saveFile function:

bool saveFile(const std::string & p_name, const std::string & p_content)
{
    std::fstream file(p_name.c_str(), std::fstream::out) ;

    if(file.is_open())
    {
        file.write(p_content.c_str(), p_content.length()) ;

        return ! file.bad() ;
    }

    return false ;
}

在这里,我用来测试这些功能的主要":

And here, the "main" I used to test those functions:

int main()
{
    const std::string name(".//myFile.txt") ;
    const std::string content("AAA BBB CCC\nDDD EEE FFF\n\n") ;

    {
        const bool success = saveFile(name, content) ;
        std::cout << "saveFile(\"" << name << "\", \"" << content << "\")\n\n"
                  << "result is: " << success << "\n" ;
    }

    {
        std::string myContent ;
        const bool success = loadFile(name, myContent) ;

        std::cout << "loadFile(\"" << name << "\", \"" << content << "\")\n\n"
                  << "result is: " << success << "\n"
                  << "content is: [" << myContent << "]\n"
                  << "content ok is: " << (myContent == content)<< "\n" ;
    }
}

更多?

如果您想做更多的事情,那么您将需要探索C ++ IOStreams库API,网址为 http://www.cplusplus.com/reference/iostream/

这篇关于从C ++文件中读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆