用于将用户输入放入文本文件的c ++代码

时间:2015-01-19 06:31:40

标签: c++

我是C ++的新手,我想帮助创建一个将费用添加到文本文件中的功能。这是文本文件中的内容吗?

费用类型:金额:日期

下面列出的是我正在使用的代码示例,但是我收到一条错误,指出函数void addExpense(char,int,int)的参数太少。

这是我正在使用的代码:

#include <iostream>
#include <fstream>

using namespace std;

void addExpense(char expense, int amount, int date){
     cout << "Type of Expense: " << endl;
     cin >> expense;
     cout << "Amount: " << endl;
     cin >> amount;
     cout << "Date: " << endl;
     cin >> date;
}

int main(int argc, char** argv) {
     addExpense();
     return 0;
} 

4 个答案:

答案 0 :(得分:1)

根据声明,方法addExpense()接受3个参数:

void addExpense(char expense, int amount, int date);

但是在调用时,你传递的是0参数:

addExpense();

相反,这样做:

addExpense(expense, amount, date);

但是,在main()中,因为您没有任何变量,请执行以下操作:

void addExpense(char expense, int amount, int date){
     //implement the logic to write to file
}

int main(int argc, char** argv) {
     char expense;
     int amount, date;
     cout << "Type of Expense: " << endl;
     cin >> expense;
     cout << "Amount: " << endl;
     cin >> amount;
     cout << "Date: " << endl;
     cin >> date;
     addExpense(expense, amount, date);
     return 0;
}

答案 1 :(得分:0)

您需要提供参数:char expense,int amount,int date。

例如:

#include <iostream>
#include <fstream>

using namespace std;

void addExpense(char expense, int amount, int date){
     cout << "Type of Expense: " << endl;
     cin >> expense;
     cout << "Amount: " << endl;
     cin >> amount;
     cout << "Date: " << endl;
     cin >> date;
}

int main(int argc, char** argv) {

     char expense;
     int amount;
     int date;

     addExpense(expense, amount, date);
     return 0;
}

答案 2 :(得分:0)

根据功能声明, 方法addExpense()接受3个参数:

void addExpense(char expense, int amount, int date);

但是在函数调用中,你传递的是0参数:

addExpense();

相反,试试这个:

char expense = e; int amount = 50, int date = 20150119; addExpense(expense, amount, date);

答案 3 :(得分:0)

我认为问题的主要内容(超出编译器错误)是关于如何写入或者更确切地追加到文本文件。

通常用于与文件交互的机制是文件流(此处:ofstream = output-filestream)。尝试向你的addExpense()函数添加一个filename参数(因为你从函数内部的用户输入中读取变量,我也会在那里声明它们而不是使它们成为参数):

void addExpense(const std::string& filename);

并在函数中添加以下代码:

void addExpense(const std::string& filename){
 //local variable declarations (no need to pass them):
 char expense;
 int amount;
 int date;

 //user input
 cout << "Type of Expense: " << endl;
 cin >> expense;
 cout << "Amount: " << endl;
 cin >> amount;
 cout << "Date: " << endl;
 cin >> date;

 //new: append a line to the file
 std::ofstream out(filename, ios::append);
 out << expense << ":" << amount << ":" << date << std::endl;
 out.close();  //important for making sure that everything is actually written to file ("flush" the stream)!
}

然后调用该函数:

addExpense("c:/myfile.txt");