C ++ add to string and write to file

Why the following code does not work

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;

int main(){
    string data;
    int i=0;

    while(i <= 5){
      i++;
      data += i;
      data += "\n";
    }

    ofstream myfile;
    myfile.open ("data.txt");
    myfile << data;
    myfile.close();
}

It should add a number , then newline and write it to a file (which does not exist yet) .

The file should look like this:

1
2
3
4
5

What is wrong with the code?

+3
source share
5 answers

Why aren't you using operator<<?

ofstream myfile;
myfile.open ("data.txt");
for ( int i = 1; i <= 5; ++i )
  myfile << i << "\n";
myfile.close();
+11
source

. , #include - , <stdio.h>, <iostream>, <string.h>, <string> <stdlib.h>, <cstdlib>.

, , . , , . data += i; " i string", . , , , .

, , . ++ ish stringstream, :

#include <iostream>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;

int main(){
    int i=0;

        stringstream ss;
    while(i <= 5){
      i++;
            ss << i << endl;
    }

    ofstream myfile;
    myfile.open ("data.txt");
    myfile << ss.str();
    myfile.close();
}
+2

, , , , .
, , , - :

while(i <= 5){
  i++;
  data += char(i+48);
  data += "\n";
}

, (48) ASCII .
EDIT: , , 6 , while(i <= 5) while(i < 5) - , while.

+1

, std::string + = (int), data += i; , , :

 data += (char) i;

:

char i='0';   

while(i <= '5'){   
  i++;   
  data += i;   
  data += "\n";   
} 

, <string.h>, ( ); <string>, ++ std::string. , stdio.h, stdlib.h string.h.

+1

sprintf :

    char temp[10]; // assuming your string rep of the number won't take >9 char.

    while(i <= MAX){
            i++;
            sprintf(temp,"%d",i);
            data += temp;
            data += "\n";
    }
+1

Source: https://habr.com/ru/post/1761352/


All Articles