thanks to the amazing chervil this code works but now i need to understand why

so i couldnt get getline to work, i didnt realise i needed to put myfile << line; in after writing getline (cin,line);

why is cin in the parenthesis and how does it (getline()) work, also am i right in thinkong i can use .c_string to pop any string reference into anything so i could do say cout << something.c_string () ; (not that i would bother with cout)



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

using namespace std;

main ()
{

string line;
string filename;


cout << "enter file name\n";
cin >> filename;
cin >> line;
ofstream myfile;
myfile.open (filename.c_str());


getline(cin,line);
myfile << line;




system ("pause");
return 0;
}
Last edited on
why is cin in the parenthesis and how does it (getline()) work, also am i right in thinkong i can use .c_string to pop any string reference into anything so i could do say cout << something.c_string () ; (not that i would bother with cout)


This is the reference for getline: http://www.cplusplus.com/reference/string/getline/

As for .c_string(), I think you mean .c_str().
take a look at the reference http://www.cplusplus.com/reference/string/string/c_str/

You use it when a plain c-string is needed (just a null-terminated array of characters) instead of the more advanced C++ string.

thank you chervil ^_^
To simplify things a little bit, you don't actually need .c_str(). You can also combine
1
2
ofstream myfile; 
myfile.open(filename);
into one line;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream> // std::cin, std::cout
#include <string>   // std::string, std::getline
#include <fstream>  // std::ofstream
using namespace std;

int main ()
{
  string line, filename;

  cout << "enter file name: ";
  getline(cin,filename);

  cout << "enter line: ";
  getline(cin,line);

  ofstream myfile(filename);
  myfile << line;

  return 0;
}


Getline works by taking whatever is in the first argument (a stream such as an ifstream, istringstream or istream) and sticking it in the second argument (a string).
Last edited on
Topic archived. No new replies allowed.