我需要改進將數據寫入文本文件的幫助。我已經成功地寫入文件,但該程序只允許我存儲一個沒有空格的字符串。所以我需要幫助的是使用一個變量將完整的句子寫入文件。 '如何將完整的句子輸入到.txt文件中C++
這裏是代碼,程序應該是一個基本的議程/計劃。
〜編輯〜 我忘了提及我正在嘗試cin數據。 例如:它詢問您的學校作業是什麼,然後鍵入「做作業」並按下回車鍵。
-shortened代碼
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "agenda.h"
using namespace std;
int main(){
string write;
string title;
string answer;
string school = "sch";
string birth = "bir";
string quit = "quit";
string view = "v";
string append = "a";
string clear = "c";
string back = "b";
string yes = y;
cout << "------Welcome User!------\n";
cout << "\nSCHOOL PLANNER\n\n";
cout << "Pick your option: \n\n" <<
"view(v)\n" <<
"append(a)\n" <<
"clear(c)\n" <<
"back(b)\n";
cin >> answer;
if(answer == view){
system("cat ~/Desktop/agenda2/school.txt");
}
else if(answer == append){
title = "Date: ";
cout << "Date: ";
cin >> write;
Write_School(title, write);
title = "Class: ";
cout << "Class: ";
cin >> write;
Write_School(title, write);
//where The problem is
title = "Assignment: ";
cout << "Assignment: ";
cin >> write;
Write_School(title, write);
cout << "[DATA SAVED]";
}
else if(answer == clear){
cout << "Are you sure you want to delete the files forever?(y/n)";
cin >> answer;
if(answer == yes){
Clear_Text();
system("clear");
cout << "Text file emptied.\n\n";
}
else{
cout << "All data saved.\n\n";
}
}
else{
cout << "[ERROR INVALID ENTRY]\n\n\n";
}
return 0;
}
//here is the header file
#ifndef agenda
#define agenda
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#endif
using namespace std;
int Write_School(string title, string write){
ofstream myfile;
myfile.open("school.txt", ios::app);
myfile << title;
myfile << write;
myfile << "\n";
myfile.close();
}
int Clear_Text(){
system("clear");
ofstream myfile;
myfile.open("school.txt");
myfile << "~School Agenda~\n\n";
myfile.close();
}
旁註 -compiled在Ubuntu終端 -cin.get和cin.getline沒有工作(除非我用他們錯了) -been尋找一個在某個地方回答很長一段時間,這是我沮喪遇害之前的最後一招!
把空格,因爲你需要他們:'myfile << title <<' ';' –
請閱讀此:http://stackoverflow.com/help/mcve – anukul