下午好!我目前正在开发一个涉及从txt文件中获取随机行的程序。在工作的过程中,我遇到了一个奇怪的问题,而文件被识别,打开,并且据说收集了一个字符串,“消息”'但是,这个变量根本没有改变值,它仍然是空的。这是代码:
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
const string Fortune = "fortune.txt";;
int main()
{
string name, junk, message;
int month, day, year, currentDay, currentMonth, currentYear, age, randNum;
time_t rawTime; // varaible for time information
struct tm *timePtr; // structure to use to store time information
ifstream fin;
timePtr = new struct tm;
time(&rawTime); //Gather value for time
localtime_s(timePtr, &rawTime);
currentDay = timePtr->tm_mday; //Set values for day/month/year
currentMonth = timePtr->tm_mon + 1;
currentYear = timePtr->tm_year + 1900;
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your year of birth: ";
cin >> year;
cout << "Enter your month of birth: ";
cin >> month;
cout << "Enter your day of birth: ";
cin >> day;
fin.open(Fortune); //Open file
getline(fin, message); //**Problem area*** Message not being received.
srand(time(0)); //Use time to ensure true randomization
randNum = rand() % 10 + 1; //Pick random value between 1-10
/* for (; randNum > 0; randNum--){ //This will help set message to the random number thus yielding a random message, though i've yet to finalize it as the message isn't working to being with
getline(fin, junk);
} */
cout << message; //Always comes up empty
system("pause");
return 0;
}
非常感谢你!
答案 0 :(得分:0)
看起来txt文件不应该在主目录中,而是它进入调试文件夹并且工作正常。谢谢,并有一个很好的