【问题标题】:Irregular code execution不规则代码执行
【发布时间】:2015-03-19 02:53:48
【问题描述】:

我一直在为当地... 地方制作一个程序,该程序将计算应订购多少比萨饼。然而,问题甚至不在于计算,而在于保存登录 ID 的文件。数据。

#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <fstream>

using namespace std;
string logs[20];

void test(ifstream& IN, string logs[], ofstream& OUT);
void introduction();
int logging_in(string id, string logs[]);
void menu();


string newl = "\n";
string dnewl = "\n\n";
string tnewl = "\n\n\n";
string qnewl = "\n\n\n\n";
string pnewl = "\n\n\n\n\n";



int main()
{

    ifstream IN;
    ofstream OUT;


    string id;

    IN.open("loginn.dat");

    cout << IN.is_open();

    test(IN, logs, OUT);



string sup;
    int receive = 0;
    introduction();










    return 0;
}

void test(ifstream& IN, string logs[], ofstream& OUT)
{
   for (int x = 0; x < 20; x++)
    {
        IN >> logs[x];
    }

    IN.close();
    OUT.open("loginn.dat");

    for (int x = 0; x < 20; x++)
    {
        OUT << logs[x] << " " << "hue" << " ";

    }
}

void introduction()
{
    string cont;

     cout << "Hello.  I am the..." << dnewl
         << "Statistical" << newl << "Pizza" << newl
         << "Order" << newl << "Amount" << newl
         << "Diagnostic." << dnewl

         << "Otherwise known as Pizzahand.  I will be assisting you to estimate the \namount of pizza that is to be ordered for <INSERT NAME>, as to \neliminate excessive ordering."
         << tnewl;

         cout << "Press Enter to continue..." << newl;
         cin.get();
}

理论上,这应该在执行其余代码之前输出数组“logs[]”。当我除了主要功能之外没有其他功能时就是这种情况。当我开始使用我的下一个函数“introduction()”时,这里读取文本文件的代码

for (int x = 0; x < 20; x++)
        {
            IN >> logs[x];
        }

似乎被打乱了。而不是在其他任何事情之前执行此任务,它似乎是在程序的最后执行它,因为我已经通过在程序仍在读取“test()”时输出其内容进行测试,但没有运气。然而,在主函数返回“0”后,我看到我的程序已正确地将数据输出到测试文件“loginns.dat”中。 我的程序必须在开始时读取此登录 ID 数据,因为当程序转换为登录时,需要该数据。另外,我尝试将这些数组和 for 循环放置在不同的位置:登录函数本身、主函数,甚至是我绝望创建的另一个函数。

我已经搜索了好几个小时来解决这个问题,但无济于事,我又试验了好几个小时。我试图解决这个问题的每一步都会导致更多的死胡同,或者更多的问题。从这个学年是学习 c++ 的第一年的意义上说,我是一个初学者,我迫切需要专家意见(或任何知识渊博的人)来帮助我面对正确的方向。

谢谢。

【问题讨论】:

  • 我试图了解您的问题,但没有成功。

标签: c++


【解决方案1】:

您只需要在写入后刷新流:

for (int x = 0; x < 20; x++)
{
    OUT << logs[x] << " " << "hue" << " ";
}
OUT.flush();

这种奇怪行为的原因是文件流在您写入文件时不一定立即写入文件。出于效率原因,它们将数据写入内部内存缓冲区(流使用的内存区域),然后在刷新缓冲区时将缓冲区内容全部写入文件。当应用程序完成时,它的所有流缓冲区都会自动刷新,这就是为什么您会在程序完成后看到文件已被写入的原因。但是,您可以自己提前冲洗它们,如上所示。当缓冲区已满时也会发生这种情况。

您还可以使用endl 令牌触发刷新,该令牌写入换行符并刷新缓冲区,如下所示:

for (int x = 0; x < 20; x++)
{
    OUT << logs[x] << " " << "hue" << " " << endl;
}

【讨论】:

  • 哇,谢谢你的解释!你的建议就像一个魅力。虽然我知道“endl”,但我不知道它实际上还有创建新线之外的作用。再次感谢!
猜你喜欢
  • 2020-04-02
  • 2011-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 2021-10-20
相关资源
最近更新 更多