我正在尝试创建用户输入名称的文本文件。它应该只创建文本文件,然后将其关闭,然后如果成功创建,则通过终端提供反馈。如果我硬编码文件名,我能够弄清楚如何创建文件,但现在我正在尝试使用用户输入我无法创建文件。现在它甚至不让我输入任何东西,它只是在我调用函数时结束。谢谢您的帮助。
编辑:我不确定是不是因为我的getline电话只是得到一个空行然后结束或为什么它不会让我cin任何东西。
EEDIT:这是我的完整代码,我想我认为不起作用的部分是,所以希望有人可以告诉我为什么我的代码在我为我的开关案例选择1之后才结束。显然我的代码并不完整,但这就是我所拥有的一切。
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
void createDB() {
ofstream db;
string filename;
cout << "Enter the name of the database you want to create: \n";
getline (cin, filename);
db.open(filename.c_str());
if(!db) { // checking if the file could be opened
cout << "\nCould not create database\n";
}// add more checks to make sure file doesn't have same name
else {
cout << "\nYour database " << filename << " was created successfully\n";
}
db.close();
}
void openDB() { // just opens hard coded file for now
// need to add check to see if one is already open
cout << "Enter the name of the database you want to open: ";
string line;
//ifstream file (
}
void closeDB() {
}
void display() {
}
void update() {
}
void create() {
}
void add() {
}
void del() {
}
int menu() {
cout << "Enter the number of the operation you wish to perform (1-9)\n"
<< "1. Create new database\n"
<< "2. Open database\n"
<< "3. Close database\n"
<< "4. Display record\n"
<< "5. Update record\n"
<< "6. Create report\n"
<< "7. Add a record\n"
<< "8. Delete a record\n"
<< "9. Quit\n";
int sel = 0;
cin >> sel;
switch (sel) {
case 1: createDB();
//menu(); // after creating file go back to list of options
break;
case 2: openDB();
break;
case 3: closeDB();
break;
case 4: display();
break;
case 5: update();
break;
case 6: create();
break;
case 7: add();
break;
case 8: del();
break;
case 9: return 0;
break;
default: cout << "Please try again and enter a valid number\n\n";
menu();
break;
}
return true; // to avoid error saying control may reach end of non-void function
}
int main() {
menu();
return 0;
}
答案 0 :(得分:0)
您发布的代码实际上是有效的,但由于您之前的代码,它似乎getline skips input。因此,如果您发布了其余代码,那将非常有用。
因此,因为您在cin
之前使用getline
,所以应在std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
之后添加cin >> sel;
。
所以你的菜单功能是
int menu() {
cout << "Enter the number of the operation you wish to perform (1-9)\n"
<< "1. Create new database\n"
<< "2. Open database\n"
<< "3. Close database\n"
<< "4. Display record\n"
<< "5. Update record\n"
<< "6. Create report\n"
<< "7. Add a record\n"
<< "8. Delete a record\n"
<< "9. Quit\n";
int sel = 0;
cin >> sel;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
switch (sel) {
case 1: createDB();
//menu(); // after creating file go back to list of options
break;
case 2: openDB();
break;
case 3: closeDB();
break;
case 4: display();
break;
case 5: update();
break;
case 6: create();
break;
case 7: add();
break;
case 8: del();
break;
case 9: return 0;
break;
default: cout << "Please try again and enter a valid number\n\n";
menu();
break;
}
return true; // to avoid error saying control may reach end of non-void function
}