2014-10-09 85 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文件不應該在主目錄中,而是它進入調試文件夾並工作正常。謝謝,並有一個很好的