Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how to open txt file?

+3 votes
asked Dec 19, 2022 by Anahit Osipyan (150 points)
#include<iostream>
#include<fstream>
#include<sstream>
#include <string>
 
using namespace std;
 
int main()
{
string filename = "random.txt";   // Name of the file

 int sum =0;float avg = 0;
string line;   // To read each line from code
int count=0;    // Variable to keep count of each line
ifstream mFile (filename);  
if(mFile.is_open())
{

while(getline(mFile, line))
{
  stringstream fun(line); //converting string to integer for addition
  int x=0;
  fun >> x;
  sum = sum + x;
  count++;
}
mFile.close(); // file closing
avg = sum/count; // Avg calculation
cout<<"Number of numbers: "<<count<<endl;
cout<<"Sum of numbers: "<<sum<<endl;
cout<<"Average of numbers: "<<avg<<endl;

}
else
cout<<"Couldn't open the file\n";
 
return 0;
}

2 Answers

0 votes
answered Dec 19, 2022 by Peter Minarik (66,990 points)

What's the question?

Your code works, all you need is a random.txt file added to your project with some content so it can be read (or you should open a different file).

0 votes
answered Dec 21, 2022 by Ericsson Lin (600 points)
If you wanted to read an input from foo.in and write an output to foo.out, then here is how you would implement it in C++:

#include <cstdio>

#include <iostream>

int main() {

    freopen("foo.in", "r", stdin);

    freopen("foo.out", "w", stdout);

    //after these two lines, you may now use "cin" and "cout" as you would regularly.

}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...