【问题标题】:C++ File input not receivingC ++文件输入未接收
【发布时间】: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 可以在项目属性中指定工作目录。

标签: c++ random getline


【解决方案1】:

看起来 txt 文件不应该在主目录中,而是在调试文件夹中并且工作正常。谢谢,祝你好运

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 2019-08-28
    • 2022-01-14
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多