Hi guys, I started learn c++ about 2 or 3 days ago. I'm getting the hang of the easy console stuff. I am running into an issue here though.
So I'm trying to create a program that allows one to read/write on to output.txt. I though I had everything set up right, but its only writing one word to the text file. Heres the code.
#include "stdafx.h"
#include <iostream> //Needed for User Input
#include <fstream> //needed for ofstream
#include <string> // needed for strings
#include <windows.h> //needed for Sleep
#include <cstdlib> //Needed for return EXIT_SUCCESS;
usingnamespace std;
int main()
{
ofstream outputfile; //allows to read and write to files
//-=ints=-//
int num1;
int begining;
//-=strings=-//
string word;
string open;
//-=Start of program=-//
cout << "File Read/Write Program" << endl; //Prints "File Read/Write Program "
cout << "Write: 1" << '\t' << endl; // Prints two options, write and read. \t makes a colum inbetween
cin >> num1; //User imput sets "num1"
outputfile.open ("output.txt"); // opens/makes output.txt file
if (num1 == 1) //If num1 = 1 one, then do this, num1 is from the users input.
{
cout << "You May Start To Write" << '\n'; //Prints "You May Start To Write". '\n creates a new line after it has been printed.
cin >> word; //Fills the string "word" with the user imput from "cin"
outputfile << word; //Saves the "word" sting into the output.txt file opened before
}
outputfile.close(); //closes outputdata.txt file
cout << "Thanks For using This Read/Write Program" << endl << "Have A Great Day";
Sleep(1500);
return EXIT_SUCCESS;
}
If I type Puppies Are Cute and go to output.txt, the only thing written in the text file is Puppies.
Any help pointing me in the write direction would be awesome!
Thanks,
Bacon.
I switched it out, and it threw an error under the period for cin.getline(word,100);. Getting rid of the string string word;and making it a char word[100] solved this problem with the error. Now it just runs through the if statement with out letting any user input at all?
I', confused..
@ModernBacon
Ignore joneele. He doesn't know what he's talking about.
the only thing you need to change is 28:
1 2
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Note that cin >> num1; left aa end of line ('\n') in the stream what is needed to be ignored at this point (before getline)
getline(cin, word); // since you don't want the word but the whole line better rename 'word' to 'line'