#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
usingnamespace std;
int main()
{
ofstream WriteToFile;
ofstream MakeFiles;
WriteToFile.open ("Names of courses.txt");
int WhileVariable = 1, NumberofCourses;
string CourseName;
cout<<"\t\t\tElective Courses Name Entry\n\n\n";
cout<<"Enter The Number of Elevtive Courses in The School: ";
cin>>NumberofCourses;
while(WhileVariable <= NumberofCourses)
{
cout<<"Enter Name of Course Number "<<WhileVariable<<": ";
getline(cin,CourseName); // THE PROBLEM IS HERE <<<<<<<<<<<<<<<<<
cout<<CourseName;
WriteToFile << CourseName << endl;
WhileVariable++;
CourseName = CourseName + ".txt";
MakeFiles.open (CourseName.c_str());
MakeFiles<<" ";
MakeFiles.close();
}
cout<<"\nYou have entered "<<NumberofCourses<<" names of courses."<<endl;
WriteToFile.close();
return 0;
}
After I run the program, I entered the 3 course names.
Let's say I entered 3 course names as shown below:
Advanced Physics
Electronics
Computer
What I would see in the file [Names of Courses.txt] would be this
Advanced Physics
Electronics
I want to enter names with spaces, but I get this error when i write words with 1 space.
Can someone explain to me why this happens and what I should do to fix it?
@eker676: That fails to handle the situation when someone enters something other than an integer for NumberofCourses. Not really an advisable solution.
I replied before I read your article. I know that cin will go crazy when invalid input is entered but ignore is just a quick and dirty fix that could be used. (although not a good choice)
stringstream myStream(input);
Create a stringstream with the value that the user has entered.
1 2
if (myStream >> myNumber)
break;
Try and convert the value stored in myStream into an integer and write it to myNumber. If this is successful (e.g returns true), then we have a valid number and can break from our loop.
cout << "Invalid number, please try again" << endl;
This line will only be executed if the above if-statement returns false. Indicating an invalid number.
>> really means write from >> to.
So when you see cin >> var; that means write a value from cin TO var.
I tried adding your code but now i have to enter the number twice and the same error that happened earlier is happening now. This is the code. I think I did something wrong!