what is wrong with this program?

后端 未结 4 1370
时光说笑
时光说笑 2021-01-27 04:54
#include 
#include 
#include 

using namespace std;

int main() {
    string x;
    getline(cin,x);
    ofstream o(\"f:/demo         


        
相关标签:
4条回答
  • 2021-01-27 05:02

    You are treating an std::string like something that it is not. It's a complex object that, somewhere in its internals, stores characters for you.

    There is no reason to assume that a character array is at the start of the object (&x), and the sizeof the object has no relation to how many characters it may indirectly hold/represent.

    You're probably looking for:

    o.write(x.c_str(), x.length());
    

    Or just use the built-in formatted I/O mechanism:

    o << x;
    
    0 讨论(0)
  • 2021-01-27 05:04

    You get exactly what you write: the binary raw value of a pointer to char...

    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    
    int main()
    {
        string x;
        getline(cin,x);
        ofstream o("tester.txt");
        o << x;
        o.close();
    }
    

    If you insist on writing a buffer directly, you can use

    o.write(x.c_str(), x.size());
    

    PS A little attention to code formatting unclouds the mind

    0 讨论(0)
  • 2021-01-27 05:22

    You seem to have an incorrect model of sizeof, so let me try to get it right.

    For any given object x of type T, the expression sizeof(x) is a compile-time constant. C++ will never actually inspect the object x at runtime. The compiler knows that x is of type T, so you can imagine it silently transforming sizeof(x) to sizeof(T), if you will.

    #include <string>
    
    int main()
    {
        std::string a = "hello";
        std::string b = "Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.";
        std::cout << sizeof(a) << std::endl;   // this prints 4 on my system
        std::cout << sizeof(b) << std::endl;   // this also prints 4 on my system
    }
    

    All C++ objects of the same type take up the exact amount of memory. Of course, since strings have vastly different lengths, they will internally store a pointer to a heap-allocated block of memory. But this does not concern sizeof. It couldn't, because as I said, sizeof operates at compile-time.

    0 讨论(0)
  • 2021-01-27 05:24

    You're passing the object's address to write into the file, whereas the original content lies somewhere else, pointed to by one of its internal pointers.

    Try this:

    string x;
    getline(cin,x);
    ofstream o("D:/tester.txt");
    o << x;
    // or
    // o.write( x.c_str() , x.length());
    
    0 讨论(0)
提交回复
热议问题