I have a long program here...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string filename;
cout << "Please enter the name of the file:\t";
getline(cin, filename);
if(filename.find('.') == string::npos)
{
char option;
string ext;
cout << "File extension not provided. Create file with .txt extension? Y/n\t";
option = getchar();
switch(option)
{
case 'n':
case 'N':
cout << "Please enter extension | <Return> to dismiss:\t";
getline(cin, ext);
if (!ext.empty()) {filename = filename + "." + ext;}
break;
case 'y':
case 'Y':
default:
filename = filename + ".txt";
break;
}
}
filename = "./files/" + filename;
int pathsize = filename.size() + 1;
char* path = new char[pathsize];
for (int i=0; i<pathsize-1; i++)
{
path[i] = filename[i];
}
path[pathsize-1] = '\0';
ofstream file;
file.open(path);
if(file.is_open())
{
cout << "\nFile created: " << filename << endl;
file.close();
}
return 0;
}
|
Line 25: Doesn't work. Doesn't even wait for input, goes ahead and puts
ext = " "
I think that is because there is already a <Return> in keyboard buffer (from
getchar()
at line 18... So, the particular
getline()
at line 25 takes that pending <Return> as end of input and sets ext to empty...
I can only think of one solution. 1) Using some other function instead of
getchar()
above... 2) Replacing
getline(cin, ext)
with
cin >> ext
...
2 is okay because I use getline simply because cin considers a white space as termination of the string. When I want sentences or strings with spaces I use getline. Since ext is supposed to be an extension, it doesn't need spaces. So I could do with cin. But there is a problem there, too. With cin, no matter how many <Return> I press, it keeps on waiting for input. Say I don't want an extension. So when the program asks for extension, I simply press <Return> to tell it "no extension" and it understands. That works with getline, but not with cin. So, cin is not a good option.
1 is IMO the best option. But I don't know which function to choose. I want a function such that I only have to press 'y' or 'n' and it takes the input (without having to press <Return>)... No <Return> pressed, no <Return> pending... That could be done by using getch() or getche() both of which are in conio.h... And I know for a fact that neither conio.h nor any of the mentioned functions are any close to being standard. I want to keep it standard and simple at the same time.
I posted another thread asking for options against 1. I didn't have any problem with getline at that time, but I wanted the input without <Return> anyway. Now, finding a solution is more important since this is effecting getline() too. That thread is located here:
http://www.cplusplus.com/forum/beginner/33659/
What do I do?