patterncppMinor
Writing and reading code from a text file
Viewed 0 times
readingfiletextwritingcodeandfrom
Problem
Using file stream object, write a program to read an external text file ("myCourse.txt") which contains all the course name and numbers you are taking this semester, and to generate an analysis (total number of courses) into an external file ("myCourseSummay.txt").
This is a past question my teacher has been hinting at us to practice, so my friend and I made this and wanted to know if would be acceptable. Personally, I think we messed the writing to the .txt file.
This is a past question my teacher has been hinting at us to practice, so my friend and I made this and wanted to know if would be acceptable. Personally, I think we messed the writing to the .txt file.
#include
#include
#include
using namespace std;
int intro()
{
cout > course1;
myCourse > course2;
myCourse > course3;
myCourse > course4;
myCourse > word;
count++;
}
cout << "Total number if courses is(are) " << count << "!";
myCourseSummary.close();
cin.get();
return 0;
}Solution
eof inside a loop conditionSee why is
eof inside a loop condition considered wrong? You do not want to do:while (!myCourseSummary.eof())
{
myCourseSummary >> word;
count++;
}You do want to do:
while (myCourseSummary >> word)
{
count++;
}Arbitrary length course names
You are reading coureses into a
char[20]. What if I have a 25-character course name? What about 50? What if it has a space in it? You need to handle all of these conditions, so you should prefer to std::getline a std::string. Actually solve the problem
The problem statement is:
read an external text file (“myCourse.txt”) which contains all the course name and numbers you are taking this semester
But you are prompting the user for course names and writing them to a file. You should read the file directly.
Also:
generate an analysis (total number of courses) into an external file (“myCourseSummay.txt”)
You are currently writing into "myCourse.txt" and reading from "myCouresSummary.txt". The question asks you to read from the first, and write a number into the latter. That is:
std::ifstream myCourse("myCourse.txt");
// do some reading
// come up with what count is
std::ofstream myCourseSummary("myCourseSummary.txt");
myCourseSummary >> count;You should be able to handle any number of courses. Just read from the file until it's done.
Code Snippets
while (!myCourseSummary.eof())
{
myCourseSummary >> word;
count++;
}while (myCourseSummary >> word)
{
count++;
}std::ifstream myCourse("myCourse.txt");
// do some reading
// come up with what count is
std::ofstream myCourseSummary("myCourseSummary.txt");
myCourseSummary >> count;Context
StackExchange Code Review Q#108890, answer score: 5
Revisions (0)
No revisions yet.