PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] How can I fix this iFile to output .txt into my console?

 August 18, 2022     c++, output     No comments   

Issue

This is a function I made in C++ to read account data from .txt files but my program closes when I open it.

static void ReadData() {
    string *line[21];
    ifstream myfile2("Userinfo1.txt");
    for (int i = 0; i < 21; i++)
    {
        if (myfile2.is_open())
        {
            while (getline(myfile2, *line[i]))
            {
                cout << *line << '\n';
            }
        }
    }
    myfile2.close();
    ifstream myfile("Userinfo2.txt");
    for (int i = 0; i < 21; i++)
    {
        if (myfile.is_open())
        {
            while (getline(myfile, *line[i]))
            {
                cout << *line << '\n';
            }
        }
    }
    myfile.close();
}

Thanks In advance for any help!


Solution

I suppose that you try to read 21 lines of file and print it. So I quickly impove your code. Firstly, there is no need to make an array of string. If you want to save this lines you could use std::vector<std::string>. Then you shouldn't check that file is open every time. And finally if you want to read all lines from file you just should check end of file. Hope I can help you.

std::string line;
ifstream myfile2("Userinfo1.txt");
if (myfile2.is_open()) {
    while (!myfile2.eof())
    {
        getline(myfile2, line);
        cout << line << '\n';
    }
}
myfile2.close();


Answered By - quest-lion
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing