2014-10-09 82 views
0

下午好!我目前正在研究一个涉及从txt文件中随机选取一行的程序。在工作时,我遇到了一个奇怪的问题,而文件被识别,打开,并且据称收集了一个字符串'message'。但是这个变量根本没有改变值,它仍然是空的。这里是代码:C++文件输入未收到

#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

在您尝试打开文件后,验证您是成功的。如果(!fin){//打印错误信息并退出} – user515430 2014-10-09 17:29:29

+0

线索将在文本文件的确切内容,使用的行结束符和已编译的系统中进行。 – 2014-10-09 17:29:35

+0

我检查了文件是否打开,但没有打开。我再次检查了这个文件,并且使用VS 2013将它命名为fortune.txt,位于与.cpp相同的文件中。我是否需要链接cpp和.txt,或者生成一个文件夹**编辑**我在记事本++中编写了txt – Dozar 2014-10-09 17:35:13

回答

0

它会出现txt文件不应该在主目录中,而是它进入调试文件夹并工作正常。谢谢,并有一个很好的