Tim S Tim S - 4 months ago 16
C++ Question

C++ Write line to text document in original order

I'm a beginner, just trying to write words and phrases into text document, on each cycle one line under another like this:

word1
word2
word3
etc.


It works with numbers, but if I use char, I got separated characters like this:

w
o
r
d
1


Can you help me figure it out with

using namespace std;

std::ofstream outfile("doc.txt", std::ios_base::app);

int main()
{
std::string a;

for (int i = 0; i < 10; i++)
{
cout << "Write word: " << endl;
cin >> a;

cout << "ID: " << i << a << endl;

outfile << a << std::endl;
}


_getch();
return 0;
}

Answer

Use std::getline() instead of operator>> to read input, one line at a time, into a std::string.

Also, since you're a beginner, now is the best time to avoid picking up bad programming habits, like using namespace std;. Stop using this, before it's too late.

Comments