How can I add a zero at the end of a string?What is the best way to read an entire file into a std::string in C++?How do you set, clear, and toggle a single bit?How do I iterate over the words of a string?How can I profile C++ code running on Linux?Can templates only be implemented in header files?Attempting to pass string to std::ifstream as argumentEasiest way to convert int to string in C++Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow can I convert a std::basic_string type to an array of char type?I want to create a function in c++ to read a file having the file as an argument, but I have problems when I compile the programPassing a string argument to ifstream

Is the negative potential of 書く used in this sentence and what is its meaning?

Why should a self-financing strategy be previsible?

How to prevent a hosting company from accessing a VM's encryption keys?

To what extent are we obligated to continue to procreate beyond having two kids?

Why does Windows store Wi-Fi passwords in a reversible format?

Papers on arXiv solving the same problem at the same time

Convergence of series of normally distributed random variables

Higman's lemma and a manuscript of Erdős and Rado

What's special ammo?

Talk interpreter

Redacting URLs as an email-phishing preventative?

Why is "-ber" the suffix of the last four months of the year?

How were medieval castles built in swamps or marshes without draining them?

Why is the UK so keen to remove the "backstop" when their leadership seems to think that no border will be needed in Northern Ireland?

Can an ISO file damage—or infect—the machine it's being burned on?

Joining lists with same elements

Why is a statement like 1 + n *= 3 allowed in Ruby?

Did Dr. Hannibal Lecter like Clarice or attracted towards her?

Half filled water bottle

Where does learning new skills fit into Agile?

Semantic difference between regular and irregular 'backen'

Is it allowed to work ONLINE on F-1 visa?

What do these commands specifically do?

Rent contract say that pets are not allowed. Possible repercussions if bringing the pet anyway?



How can I add a zero at the end of a string?


What is the best way to read an entire file into a std::string in C++?How do you set, clear, and toggle a single bit?How do I iterate over the words of a string?How can I profile C++ code running on Linux?Can templates only be implemented in header files?Attempting to pass string to std::ifstream as argumentEasiest way to convert int to string in C++Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow can I convert a std::basic_string type to an array of char type?I want to create a function in c++ to read a file having the file as an argument, but I have problems when I compile the programPassing a string argument to ifstream






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








-1















I'm trying to read some text out of a file called "file.dat". The problem is, that the string in the file does not include a zero at the end as for standard C. So I need something that adds the zero, so I can work with the string without getting random symbols after the string when I print it.



void cSpectrum::readSpectrum(const std::string &filename, double 
tubeVoltage, double &minEnergy, std::string &spectrumName)

//Object with the name "inp" of the class ifstream
ifstream inp(filename, ios::binary);

//Checks if the file is open
if (!inp.is_open())
throw runtime_error("File not open!");


cout << "I opened the file!" << endl;

//Check the title of the file
string title;
char *buffer = new char[14];
inp.read(buffer, 14);

cout << buffer << endl;



At the moment I get the following output, I would like to get it without the ²²²²┘.



I opened the file!



x-ray spectrum²²²²┘










share|improve this question



















  • 2





    Maybe just use a std::string instead of all the manual memory management and char* gunk that you are currently doing.

    – Jesper Juhl
    Mar 27 at 20:00












  • Is the file really binary?

    – ttemple
    Mar 27 at 20:01











  • Is it really a binary file or is it a text file? If it's really a binary file, treating it like you can trust it's a text file is probably a problem. If you want to dump the contents, you probably should dump them one character at a time, because it might have, you know, binary data. If it's a text file, then you should open it as a text file and read into a string. However, Remy's answer isn't horrible.

    – Joseph Larson
    Mar 27 at 20:01











  • Yes, it is a .dat file

    – thefighter3
    Mar 27 at 20:03











  • @thefighter3 "it is a .dat file" - the name of the file, including its extension (.dat in this case) means nothing. You can name a PNG file ".txt" if you want to, that doesn't turn the image into a text document. You cannot infer anything from the file name alone.

    – Jesper Juhl
    Mar 27 at 20:28

















-1















I'm trying to read some text out of a file called "file.dat". The problem is, that the string in the file does not include a zero at the end as for standard C. So I need something that adds the zero, so I can work with the string without getting random symbols after the string when I print it.



void cSpectrum::readSpectrum(const std::string &filename, double 
tubeVoltage, double &minEnergy, std::string &spectrumName)

//Object with the name "inp" of the class ifstream
ifstream inp(filename, ios::binary);

//Checks if the file is open
if (!inp.is_open())
throw runtime_error("File not open!");


cout << "I opened the file!" << endl;

//Check the title of the file
string title;
char *buffer = new char[14];
inp.read(buffer, 14);

cout << buffer << endl;



At the moment I get the following output, I would like to get it without the ²²²²┘.



I opened the file!



x-ray spectrum²²²²┘










share|improve this question



















  • 2





    Maybe just use a std::string instead of all the manual memory management and char* gunk that you are currently doing.

    – Jesper Juhl
    Mar 27 at 20:00












  • Is the file really binary?

    – ttemple
    Mar 27 at 20:01











  • Is it really a binary file or is it a text file? If it's really a binary file, treating it like you can trust it's a text file is probably a problem. If you want to dump the contents, you probably should dump them one character at a time, because it might have, you know, binary data. If it's a text file, then you should open it as a text file and read into a string. However, Remy's answer isn't horrible.

    – Joseph Larson
    Mar 27 at 20:01











  • Yes, it is a .dat file

    – thefighter3
    Mar 27 at 20:03











  • @thefighter3 "it is a .dat file" - the name of the file, including its extension (.dat in this case) means nothing. You can name a PNG file ".txt" if you want to, that doesn't turn the image into a text document. You cannot infer anything from the file name alone.

    – Jesper Juhl
    Mar 27 at 20:28













-1












-1








-1








I'm trying to read some text out of a file called "file.dat". The problem is, that the string in the file does not include a zero at the end as for standard C. So I need something that adds the zero, so I can work with the string without getting random symbols after the string when I print it.



void cSpectrum::readSpectrum(const std::string &filename, double 
tubeVoltage, double &minEnergy, std::string &spectrumName)

//Object with the name "inp" of the class ifstream
ifstream inp(filename, ios::binary);

//Checks if the file is open
if (!inp.is_open())
throw runtime_error("File not open!");


cout << "I opened the file!" << endl;

//Check the title of the file
string title;
char *buffer = new char[14];
inp.read(buffer, 14);

cout << buffer << endl;



At the moment I get the following output, I would like to get it without the ²²²²┘.



I opened the file!



x-ray spectrum²²²²┘










share|improve this question














I'm trying to read some text out of a file called "file.dat". The problem is, that the string in the file does not include a zero at the end as for standard C. So I need something that adds the zero, so I can work with the string without getting random symbols after the string when I print it.



void cSpectrum::readSpectrum(const std::string &filename, double 
tubeVoltage, double &minEnergy, std::string &spectrumName)

//Object with the name "inp" of the class ifstream
ifstream inp(filename, ios::binary);

//Checks if the file is open
if (!inp.is_open())
throw runtime_error("File not open!");


cout << "I opened the file!" << endl;

//Check the title of the file
string title;
char *buffer = new char[14];
inp.read(buffer, 14);

cout << buffer << endl;



At the moment I get the following output, I would like to get it without the ²²²²┘.



I opened the file!



x-ray spectrum²²²²┘







c++ visual-studio-2017






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 19:57









thefighter3thefighter3

172 silver badges9 bronze badges




172 silver badges9 bronze badges










  • 2





    Maybe just use a std::string instead of all the manual memory management and char* gunk that you are currently doing.

    – Jesper Juhl
    Mar 27 at 20:00












  • Is the file really binary?

    – ttemple
    Mar 27 at 20:01











  • Is it really a binary file or is it a text file? If it's really a binary file, treating it like you can trust it's a text file is probably a problem. If you want to dump the contents, you probably should dump them one character at a time, because it might have, you know, binary data. If it's a text file, then you should open it as a text file and read into a string. However, Remy's answer isn't horrible.

    – Joseph Larson
    Mar 27 at 20:01











  • Yes, it is a .dat file

    – thefighter3
    Mar 27 at 20:03











  • @thefighter3 "it is a .dat file" - the name of the file, including its extension (.dat in this case) means nothing. You can name a PNG file ".txt" if you want to, that doesn't turn the image into a text document. You cannot infer anything from the file name alone.

    – Jesper Juhl
    Mar 27 at 20:28












  • 2





    Maybe just use a std::string instead of all the manual memory management and char* gunk that you are currently doing.

    – Jesper Juhl
    Mar 27 at 20:00












  • Is the file really binary?

    – ttemple
    Mar 27 at 20:01











  • Is it really a binary file or is it a text file? If it's really a binary file, treating it like you can trust it's a text file is probably a problem. If you want to dump the contents, you probably should dump them one character at a time, because it might have, you know, binary data. If it's a text file, then you should open it as a text file and read into a string. However, Remy's answer isn't horrible.

    – Joseph Larson
    Mar 27 at 20:01











  • Yes, it is a .dat file

    – thefighter3
    Mar 27 at 20:03











  • @thefighter3 "it is a .dat file" - the name of the file, including its extension (.dat in this case) means nothing. You can name a PNG file ".txt" if you want to, that doesn't turn the image into a text document. You cannot infer anything from the file name alone.

    – Jesper Juhl
    Mar 27 at 20:28







2




2





Maybe just use a std::string instead of all the manual memory management and char* gunk that you are currently doing.

– Jesper Juhl
Mar 27 at 20:00






Maybe just use a std::string instead of all the manual memory management and char* gunk that you are currently doing.

– Jesper Juhl
Mar 27 at 20:00














Is the file really binary?

– ttemple
Mar 27 at 20:01





Is the file really binary?

– ttemple
Mar 27 at 20:01













Is it really a binary file or is it a text file? If it's really a binary file, treating it like you can trust it's a text file is probably a problem. If you want to dump the contents, you probably should dump them one character at a time, because it might have, you know, binary data. If it's a text file, then you should open it as a text file and read into a string. However, Remy's answer isn't horrible.

– Joseph Larson
Mar 27 at 20:01





Is it really a binary file or is it a text file? If it's really a binary file, treating it like you can trust it's a text file is probably a problem. If you want to dump the contents, you probably should dump them one character at a time, because it might have, you know, binary data. If it's a text file, then you should open it as a text file and read into a string. However, Remy's answer isn't horrible.

– Joseph Larson
Mar 27 at 20:01













Yes, it is a .dat file

– thefighter3
Mar 27 at 20:03





Yes, it is a .dat file

– thefighter3
Mar 27 at 20:03













@thefighter3 "it is a .dat file" - the name of the file, including its extension (.dat in this case) means nothing. You can name a PNG file ".txt" if you want to, that doesn't turn the image into a text document. You cannot infer anything from the file name alone.

– Jesper Juhl
Mar 27 at 20:28





@thefighter3 "it is a .dat file" - the name of the file, including its extension (.dat in this case) means nothing. You can name a PNG file ".txt" if you want to, that doesn't turn the image into a text document. You cannot infer anything from the file name alone.

– Jesper Juhl
Mar 27 at 20:28












2 Answers
2






active

oldest

votes


















3















Simply allocate +1 more char for your array, but don't read into that char, just set it to 0:



char buffer[15];
inp.read(buffer, 14);
buffer[14] = '';
cout << buffer << endl;


Or, simply don't use a char[] at all, use std::string instead, see:



What is the best way to read an entire file into a std::string in C++?






share|improve this answer
































    0















    I did it with the std::string now. If you want you can replace the 14 by an integer variable.



    void cSpectrum::readSpectrum(const std::string & filename, double tubeVoltage, double 
    & minEnergy, std::string const & spectrumName)

    ifstream inp(filename, ios::binary);

    //Checks if the file is open
    if (!inp.is_open())
    throw runtime_error("ERROR: Could not open the file!");


    //Reads the title
    string title(14, '');
    inp.read(&title[0], 14);

    //If it is not the correct file throw an ERROR
    if (title != spectrumName)
    throw runtime_error("ERROR: Wrong file title");

    readSpectrum(inp, tubeVoltage, minEnergy, spectrumName);






    share|improve this answer



























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385495%2fhow-can-i-add-a-zero-at-the-end-of-a-string%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3















      Simply allocate +1 more char for your array, but don't read into that char, just set it to 0:



      char buffer[15];
      inp.read(buffer, 14);
      buffer[14] = '';
      cout << buffer << endl;


      Or, simply don't use a char[] at all, use std::string instead, see:



      What is the best way to read an entire file into a std::string in C++?






      share|improve this answer





























        3















        Simply allocate +1 more char for your array, but don't read into that char, just set it to 0:



        char buffer[15];
        inp.read(buffer, 14);
        buffer[14] = '';
        cout << buffer << endl;


        Or, simply don't use a char[] at all, use std::string instead, see:



        What is the best way to read an entire file into a std::string in C++?






        share|improve this answer



























          3














          3










          3









          Simply allocate +1 more char for your array, but don't read into that char, just set it to 0:



          char buffer[15];
          inp.read(buffer, 14);
          buffer[14] = '';
          cout << buffer << endl;


          Or, simply don't use a char[] at all, use std::string instead, see:



          What is the best way to read an entire file into a std::string in C++?






          share|improve this answer













          Simply allocate +1 more char for your array, but don't read into that char, just set it to 0:



          char buffer[15];
          inp.read(buffer, 14);
          buffer[14] = '';
          cout << buffer << endl;


          Or, simply don't use a char[] at all, use std::string instead, see:



          What is the best way to read an entire file into a std::string in C++?







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 27 at 20:01









          Remy LebeauRemy Lebeau

          360k21 gold badges287 silver badges486 bronze badges




          360k21 gold badges287 silver badges486 bronze badges


























              0















              I did it with the std::string now. If you want you can replace the 14 by an integer variable.



              void cSpectrum::readSpectrum(const std::string & filename, double tubeVoltage, double 
              & minEnergy, std::string const & spectrumName)

              ifstream inp(filename, ios::binary);

              //Checks if the file is open
              if (!inp.is_open())
              throw runtime_error("ERROR: Could not open the file!");


              //Reads the title
              string title(14, '');
              inp.read(&title[0], 14);

              //If it is not the correct file throw an ERROR
              if (title != spectrumName)
              throw runtime_error("ERROR: Wrong file title");

              readSpectrum(inp, tubeVoltage, minEnergy, spectrumName);






              share|improve this answer





























                0















                I did it with the std::string now. If you want you can replace the 14 by an integer variable.



                void cSpectrum::readSpectrum(const std::string & filename, double tubeVoltage, double 
                & minEnergy, std::string const & spectrumName)

                ifstream inp(filename, ios::binary);

                //Checks if the file is open
                if (!inp.is_open())
                throw runtime_error("ERROR: Could not open the file!");


                //Reads the title
                string title(14, '');
                inp.read(&title[0], 14);

                //If it is not the correct file throw an ERROR
                if (title != spectrumName)
                throw runtime_error("ERROR: Wrong file title");

                readSpectrum(inp, tubeVoltage, minEnergy, spectrumName);






                share|improve this answer



























                  0














                  0










                  0









                  I did it with the std::string now. If you want you can replace the 14 by an integer variable.



                  void cSpectrum::readSpectrum(const std::string & filename, double tubeVoltage, double 
                  & minEnergy, std::string const & spectrumName)

                  ifstream inp(filename, ios::binary);

                  //Checks if the file is open
                  if (!inp.is_open())
                  throw runtime_error("ERROR: Could not open the file!");


                  //Reads the title
                  string title(14, '');
                  inp.read(&title[0], 14);

                  //If it is not the correct file throw an ERROR
                  if (title != spectrumName)
                  throw runtime_error("ERROR: Wrong file title");

                  readSpectrum(inp, tubeVoltage, minEnergy, spectrumName);






                  share|improve this answer













                  I did it with the std::string now. If you want you can replace the 14 by an integer variable.



                  void cSpectrum::readSpectrum(const std::string & filename, double tubeVoltage, double 
                  & minEnergy, std::string const & spectrumName)

                  ifstream inp(filename, ios::binary);

                  //Checks if the file is open
                  if (!inp.is_open())
                  throw runtime_error("ERROR: Could not open the file!");


                  //Reads the title
                  string title(14, '');
                  inp.read(&title[0], 14);

                  //If it is not the correct file throw an ERROR
                  if (title != spectrumName)
                  throw runtime_error("ERROR: Wrong file title");

                  readSpectrum(inp, tubeVoltage, minEnergy, spectrumName);







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 4 at 15:46









                  thefighter3thefighter3

                  172 silver badges9 bronze badges




                  172 silver badges9 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385495%2fhow-can-i-add-a-zero-at-the-end-of-a-string%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현