【发布时间】:2014-10-09 17:25:48
【问题描述】:
下午好!我目前正在开发一个程序,该程序涉及从 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;
}
非常感谢您!
【问题讨论】:
-
在您尝试打开文件后,请验证您是否成功。 if (!fin){ // 打印错误信息并退出 }
-
线索将在文本文件的确切内容、使用的行尾和编译的系统中。
-
我检查了文件是否已打开,但没有。我仔细检查了该文件,它被命名为 fortune.txt,位于与 .cpp 相同的文件中,使用 VS 2013。我是否需要以某种方式链接 cpp 和 .txt,或者创建一个文件夹 Edit 我在notepad++中写了txt
-
@Dozar 可以在项目属性中指定工作目录。