将包含多个空格的字符串添加到文本文件中

时间:2015-01-20 08:31:14

标签: c++

我有以下代码,我正在为文本文件添加费用,但是当我运行代码时,文件的输入变为

:200:25jan

我使用getline(cin,expense);要使整个字符串在线,但结果空白,需要一些帮助

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
void addExpense(string& expense, double& amount, string& date){ 
cout << "Type of Expense: " << endl;
getline(cin, expense);
cin.clear();
cin.ignore(100, '\n');
cout << "Amount: " << endl;
cin >> amount;
cin.clear();
cin.ignore(100, '\n');
cout << "Transaction Date: " << endl;
getline (cin, date);
cin.clear();
cin.ignore(100, '\n');
}

int main() {
char choice;
bool expenseOn = true;
while (expenseOn != false){
 cout << "a) Add Expense\n";   
 cout << "b) Remove Expense\n";
 cout << "c) Edit Cash Flow item for Expense or Income\n";
 cout << "d) Net Cash Flow Summary Report\n";
 cout << "e) Quit\n";
 cout << "\n";
 cout << "Please Enter a Choice:\n";

 cin.clear ();
 cin >> choice;

 string date = "", expense = "", texpense = "";
 ofstream outfile;
 double amount = 0.0;

switch (choice){
    case 'a':
        cout << "Add Expense.\n";
        //char fileName[20];
        /*cout << "Enter filename.." << endl;
        cin >> fileName;*/ 
        outfile.open ("Expense.txt");
        if (!outfile)
        {
        cout << "File Storing Failed" << endl;
        exit(-1);
        }
        addExpense(expense, amount, date);
        outfile << expense << ":" << amount << ":" << date;
        break;
     }

2 个答案:

答案 0 :(得分:1)

您误用了ignore - 当且仅当您确实需要跳到下一行时才应该使用它。
当您使用getline时,您将从流中提取整行(包括换行符) 当您使用>>时,新行将保留在流中以便稍后阅读。

这就是:

void addExpense(string& expense, double& amount, string& date){ 
    cout << "Type of Expense: " << endl;
    getline(cin, expense);   // Read the newline that was left after reading 'choice'
    cin.clear();
    cin.ignore(100, '\n');   // Read the line containing the type of expense 
    cout << "Amount: " << endl;
    cin >> amount;           // Read the amount
    cin.clear();
    cin.ignore(100, '\n');   // Read to the end of line
    cout << "Transaction Date: " << endl;
    getline (cin, date);     // Read the line containing the date
    cin.clear();
    cin.ignore(100, '\n');   // Read to the end of line
}

(您可能已经注意到,您需要在日期之后按Enter两次才能继续。第二个是最终ignore正在等待的内容。)

ignore之后移除getline,然后在cin >> choice之后添加一个。{/ p>

答案 1 :(得分:1)

此问题的另一个可能答案

string expense = "", date = "", type = "";
double amount = 0.0;
ofstream outfile; 
outfile.open ("Expense.txt", std::ios_base::app);
if (!outfile)
{
cout << "File open fail" << endl;
exit(-1);
}
cout << "Please Enter Expense: ";
cin.ignore();
getline(cin, expense);
cin.clear();
cout << "Amount: " << endl;
cin >> amount;      
cin.clear();
cout << "Transaction Date: " << endl;
cin.ignore(100,'\n');
getline (cin, date);
outfile << expense << ":" << amount << ":" << date << "\n";