Reputation:
I am writing a program that should be able to take input, create a file, and store that information. I have successfully done that part. The program should also be able to print a previous file to the screen. The problem I get is that it cuts off the first word on the first line of the file call. For example, I would click n
and input a previous text file such as test.txt
and it would print the following:
Kennedy
CSC 201
Computer Science
Mondays and Wednesdays
Scott Davis
when it should print:
John Kennedy
CSC 201
Computer Science
Mondays and Wednesdays
Scott Davis
What did I do wrong for file printing?
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
ifstream inData;
ofstream outData;
string inFile, outFile, fullName, fileName;
string courseCode, courseName, courseProfessor, courseHours;
char answer;
int counter = 0;
int courses;
cout << "Are you creating a new file? y/n" << endl;
cin >> answer;
if(answer == 'n')
{
cout << "Enter the name of your file." << endl;
cin >> inFile;
cin.ignore (200, '\n');
inData.open(inFile.c_str());
inData >> fileName;
cout << inData.rdbuf();
}
else if(answer == 'y')
{
cout << "Enter the name of your file." << endl;
cin >> outFile;
cin.ignore (200, '\n');
outData.open(outFile.c_str());
cout << "What is your full name?" << endl;
getline(cin, fullName);
outData << fullName << endl;
outData << endl;
cout << "How many courses are you taking?" << endl;
cin >> courses;
while(courses > counter)
{
cin.ignore (200, '\n');
cout << "What is the code for your class?" << endl;
getline(cin, courseCode);
outData << courseCode << endl;
cout << "What is the name of the course?" << endl;
getline(cin, courseName);
outData << courseName << endl;
cout << "What days and time periods do you take this course?" << endl;
getline(cin, courseHours);
outData << courseHours << endl;
cout << "What is the name of your professor?" << endl;
getline(cin, courseProfessor);
outData << courseProfessor << endl;
outData << endl;
counter++;
}
}
inData.close();
outData.close();
return 0;
}
Upvotes: 0
Views: 895
Reputation: 2520
Your problem is inData >> fileName;
after inData.open(inFile.c_str());
It will read the first word into fileName and move the current file position.
Upvotes: 1