如何检查ifstream文件末尾是否有新行。 (C ++)

时间:2016-01-26 13:26:45

标签: c++ arrays input newline ifstream

如果\n文件末尾有ifstream,我的程序可以正常运行。

任务是这样的: 定义产品的结构 (产品名称,类别,价格,库存数量)。 来自File trgovina.txt(它可能已包含预定义的产品。"在我发布的图片中相似) 通过功能:

  1. 1从现有文件tgovina.txt
  2. 将产品加载到数组中
  3. 2允许从文件proizvodi.txt打印产品名称(新行中的每个产品)
  4. 按类别启用产品搜索 (从用户加载类别并在屏幕上打印出产品和类别的名称,并打印到名为&#34的文件中;所需类别")
  5. 在文件lessthen10.txt
  6. 中启用小于10库存的产品打印
  7. 允许打印最昂贵,最便宜的产品
  8. 允许新产品进入数据库(将其写入文件trgovina.txt)
  9. 问题开始here:如果此人停止在第一个黄色标记处写字,我想添加一个新行,这样当我想添加新文本时,它将以新行开头。如果文本文件末尾已有新行,我想继续写,不添加新行。

    第二个问题是如果ofstream文件没有文本:在这种情况下,我不想添加新行。

    ofstream dat("trgovina.txt", std::ios_base::app);
    if (!dat)
    {
      cout << "Mistake!" << endl;
      return;
    }
    string name;
    string category;
    bool a = true;
    double price;
    int quantity;
    while (a)
    {   
      **//Here I want to check if there is a "\n" sign at the end of text
        //if there isn't I want to add one, and then continue writing.
        // But if the text file was empty i dont want to add new line**
    
      cout << "enter the name of new product: ";
      getline(cin, name);
      dat << name << "|";
      cout << "enter the category of new product: ";
      getline(cin, category);
      dat << category << "|";
      cout << "enter the price of new product: ";
      cin >> price;
      dat << price << "|";
      cout << "enter the quantity of new product: ";
      cin >> quantity;
      dat << quantity << endl; **//This works if the txt file is empty or if 
                                 //there is "\n" at the end**
      cout << "more? (1 / 0)";
      cin >> a;
      cin.ignore();
      system("cls");
    };
    dat.close();
    

    抱歉我的英语不好。

    我使用

    收到错误
    while (a)
    {   
        trgovina.seekg(-1); 
        char c;
        trgovina.get(c);
        if (c == '\n')
        {
    
        }
        else
        {
            dat << endl;
        }
    

    这是从此代码运行几行新行后txt文件的图片Picture。如果文件是空的,它会在顶部添加一个新行,如果不是,它会运行良好。

1 个答案:

答案 0 :(得分:0)

它是一个index.html,所以你只能写一个流。你需要的是阅读(确定内部)和写(添加项目),这称为make_presentation.slides.html。您可以阅读,写入和寻找ofstream。要确定它的最后一个字符是否是换行符,只需查找最后一个字符并使用类似的字符读取它:

fstream