I was able to finally produce a working code on inputting and displaying n student details (Student ID#, Name and Age)... although the name is not full name capable, I would like to write these inputs to a text file and then read from text file also. I will appreciate any help, please:
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fstream>
using namespace std;
struct student
{
int sno, sage;
char sname[100];
};
int main(int e, char* argv[])
{
struct student s[e];
int i;
ofstream outfile;
outfile.open("info.txt");
printf("How many entries are you making?: ");
scanf("%d",&e);
printf(" \n");
printf("Please enter Student Information:\n");
for(i=0;i<e;++i)
{
s[i].sno=i+1;
printf("\nEnter Information for student %d\n",s[i]);
printf("================================\n");
cout<<"\nEnter (4 digits) student ID No: ";
cin>>s[i].sno;
cout<<"\nEnter student's name: ";
cin>>s[i].sname;
cout<<"\nAge of student: ";
cin>>s[i].sage;
printf("\n");
//If i do this, I get only first set of data
outfile <<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
/*I am trying to get data into txt file using the loop below but it looks odd and it collects some of the first set of data, and completes it like this: 1212 kop 23
1627953384 1629646589*/
/*for(i=0;i<e;++i)
{
outfile <<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
}*/
outfile.close();
}
printf("Displaying information of student(s):\n");
printf("==================================\n");
for(i=0;i<e;++i)
{
printf("\nInformation for Student %d:\n",i+1);
cout<<"\nStudent ID:"<<s[i].sno;
cout<<"\nStudent name: "<<s[i].sname;
cout<<"\nAge of student: "<<s[i].sage;
printf("\n\n");
}
return 0;
}
I suggest starting with a simple program that writes to a file:
#include <fstream>
#include <iostream>
#include <cstdlib>
int main(void)
{
std::ofstream output_file("text.txt");
std::cout << "Writing to output file.\n";
output_file << "This is my text.\n";
output_file.flush();
std::cout << "Finished writing to file.\n";
output_file.close();
std::cout << "Paused. Press Enter to continue.\n";
std::cin.ignore(100000, '\n');
return EXIT_SUCCESS;
}
After executing the above program, you should verify that the text file contains the correct text.
Next, you can add other code, such as prompting the User and obtaining the input.
I think you don't know how to read or write through file. That's why you are having problem. There are two ways which people generally use. Go through these two sample tutorial for good understanding of these methods.
- c methods
- c++ methods
This is your code which I've modified to read and write from files using both methods -
Given Input file - student.txt. //first line No. of input
2
1234 manish 34
4321 mukesh 43
Code
#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;
struct student
{
int sno, sage;
char sname[50];
};
//Read data using C Method
void ReadAndWriteCMethod(){
student s[100];
FILE* f;
f = fopen("student.txt","r");
int N;
fscanf(f,"%d",&N);
**//Reading from file**
for(int i=0; i<N; i++){
fscanf(f,"%d %s %d",&s[i].sno, &s[i].sname, &s[i].sage);
}
fclose(f);
**//Writing over file**
f = fopen("wstudent1.txt","w+");
for(int i=0; i<N; i++){
cout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
fprintf(f,"%d %s %d\n",s[i].sno,s[i].sname,s[i].sage);
}
fclose(f);
}
//Reading and writing using C++
void ReadAndWriteCPlusPlusMethod(){
student s[100];
**// Reading data**
std::ifstream fin("student.txt");
char s2[100];
int N; fin>>N;
for(int i=0; i<N; i++){
fin>>s[i].sno>>s[i].sname>>s[i].sage;
cout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
}
fin.close();
**//Writing data**
std::ofstream fout("wstudent2.txt");
for(int i=0; i<N; i++){
fout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
}
fout.close();
}
int main()
{
ReadAndWriteCMethod();
ReadAndWriteCPlusPlusMethod();
}
After running, this will generate two files wstudent1.txt and wstudent2.txt files.
Related
#include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
string arr[3][2];
int i =0,j=0;
ofstream out ("test1.dat" , ios::app);
string name;
while(true)
{
cin>>name;
if(name=="end")
break;
out << name <<' ' ;
}
out.close();
ifstream in ("test1.dat", ios::in);
in >> name;
while(!in.eof())
{
arr[i][j]=name;
in>>name;
j++;
arr[i][j]=name;
i++;
j=0;
}
in.close();
for(i=0;i<3;i++){
cout<<endl;
for(j=0;j<2;j++){
cout<<arr[i][j]<<" ";}
}
return 0;
}
please help i have run-time error with this.what is my problem?i want to write some data in a file then read them and put them in an array and then print the array.i want to write and read the file by string not by character.sorry about my weak english.
thanks
Try adding a condition for i in your while loop.
This fixes your run-time error with the array bounds but you still have a logic error (unless you want duplicate occurrences of the same word in your array?)
while(!in.eof() && i < 3)
{
arr[i][j]=name;
in>>name;
j++;
arr[i][j]=name;
i++;
j=0;
}
I have a .txt file which contains numbers and looks like this:
1
2
3
etc
The numbers are unimportant but they all start on a new line.
I want to then find the sum & mean of the numbers in the text file.
Here's what I have so far:
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
int sum(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
int x(0);
cout<<"numbers.txt";
cin>> file_name;
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin>>x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl;
fin>>x;
sum=sum+x;
sumcount++;
if(x%2==0)
even++;
else
odd++;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl;
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
The start loads the numbers but it won't execute the next step.
i have looked at a lot of other code and tried to implement other ideas to solve the problem; however, some people use loops and arrays and other things and I'm not sure which to use.
How can I get my program to find the sum and mean of numbers in the file?
also any other links for help would be appreciated
EDIT: although the numbers are intergers the mean may not be
Here is your working code.
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a = 0;
myfile >> a;
while (!myfile.fail())
{
printf("%f ", a);
myfile >> a; // here you dispay your numbers
}
getchar(); // waiting for input
float sum(0);
int x(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
cout<<"numbers.txt" << endl;
cin>> file_name; // waiting for enter file name
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin >> x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl; // display number again
sum=sum+x;
sumcount++;
if(x % 2==0) // compuing your file statistics
even++;
else
odd++;
fin>>x;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl; // displaying results
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
I have added some minimal alteration to make your program work correctly.
the result
and more
As soon as your main function encounters the statement return 0 it will exit the program and fail to execute the remaining code. This should generally appear only once in your main function, at the end of your code block
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n=0;
int sum=0,total=0;
fstream file("numbers.txt");
while(file >> n) // or while(cin >> n) to read from stdin, commandline
{
sum += n;
total++;
}
int average = (float) sum/total;
cout<<"sum: " << sum << endl;
cout << "average: " << average << endl;
return 0;
}
#include <iostream>
#include<fstream>
int main()
{
std::ifstream txtFile;
txtFile.open("data.txt");
//TODO: check if the file fails to open.
double tempNum, mean(0.0), sum(0.0), count(0.0);
while (txtFile >> tempNum)
{
sum += tempNum;
++count;
}
mean = sum/count;
std::cout << "mean: " << mean << " sum: " << sum << std::endl;
return 0;
}
Hey guys I stuck working on an assignment in which I asked to write a program that lists the contents of a file.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string array[5];
ifstream infile("file_names.txt");
int x=0;
while(infile>>array[x++]){
for(int i=0;i<=x;i++){
infile >> array[i];
cout << array[i] << endl;}}
}
basically I have a file named "file_names.txt" that contains three strings and I want my program to list them.
you don't need two loops.
int main() {
int array_size=5;
string array[array_size];
ifstream infile("file_names.txt");
int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
cout << array[i] << endl;
i++;
}
}
Your assignment was
an assignment in which I asked to write a program that lists the contents of a file.
One way of printing the contents of a file could be
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("my_file.txt", ios::in); // open input stream
if(!fin){ // check state, that file could be successfully opened
printf("Error opening file.");
return 1;
}
while(fin.peek() != EOF){
cout << (char)fin.get();
}
fin.close(); // close input stream
return 0;
}
This code demonstrates some basic C++ functionality like
opening an input stream, checking the state of the input stream and reading the contents character by character. Try to understand each step.
I know I can get to the same result like this
string array[50];
ifstream infile("file_names.txt");
for(int i=0; **i<3**; i++){
infile >> array[i];
cout << array[i] <<endl;}
But the whole point is to use a while loop because there might be more or less than 3 items
I wrote a quick C++ program that asks the user for a input text file and an output text file. The program is then supposed to number the lines in the file on the left margin. However, I cannot seem to get it working properly, it compiles fine but does not number the lines like it is supposed to. I believe it is a logical error on my part. I am also not too familiar with file i/o in C++ as I am just learning it now using old school textbooks.
Here is the file:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
int main(void)
{int i = 0 , num = 1;
string inputFileName;
string outputFileName;
string s;
ifstream fileIn;
ofstream fileOut;
char ch;
cout<<"Enter name of input file: ";
cin>>inputFileName;
cout<<"Enter name of output file: ";
cin>>outputFileName;
fileIn.open(inputFileName.data());
fileOut.open(outputFileName.data());
assert(fileIn.is_open() );
assert(fileOut.is_open() );
while (!(fileIn.eof()))
{ch=fileIn.get();
if (ch=='\n') num++;
fileOut << num << "\n";
s.insert(i,1,ch); //insert character at position i
i++;
}
fileOut << s;
fileIn.close();
fileOut.close();
return 0;
}
If anyone could point me in thr right direction or give me some tips I would be eternally grateful.
int i = 0;
string line;
while (getline(infile, line))
{
outfile << (i++) << " " << line << "\n";
}
So, this program is meant to have three parallel arrays that carry the names of ten account holders, their IDs, and their balances. My main file looks like this:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include "IOFunctions.h" // My header file
using namespace std;
int main ()
{
const int AR_SIZE = 10;
string nameAr;
int idAr;
float balanceAr;
// F U N C T I O N -- ReadInData
ReadInData(nameAr,
idAr,
balanceAr,
AR_SIZE);
}
The error I'm getting looks like this: http://i.imgur.com/1eHOZ7K.png
Now, the header file looks like this:
#ifndef IOFUNCTIONS_H_ // This is my own header
#define IOFUNCTIONS_H_
#include <iomanip>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string ReadInData(string nameArray[],
int idArray[],
float balanceArray[],
const int ARRAY_SIZE)
{
ifstream inFile;
string inFileName;
string outFileName;
// INPUT -- Prompts user for input file name
cout << left << setw(40)
<< "What input file would you like to use? ";
getline(cin, inFileName);
// Checks that the file name entered is accessible
while(inFileName != "InFile.txt")
{
cout << setw(40) << "Please enter a valid file name: ";
getline(cin, inFileName);
}
// INPUT -- Prompts user for output file name
cout << setw(40)
<< "What output file would you like to use? ";
getline(cin, outFileName);
// Checks that the file name entered is accurate to assignment
while(outFileName != "OFile.txt")
{
cout << setw(40) << "Please enter a valid file name: ";
getline(cin, outFileName);
}
// PROCESSING -- Takes the data from the input file and assigns it
// to the names array, ID array, and balance array
// NAME ARRAY
inFile.open(inFileName.c_str());
for(int index = 0; index < ARRAY_SIZE; index++)
{
inFile >> nameArray[index];
}
inFile.close();
// ID ARRAY
inFile.open(inFileName.c_str());
for(int index = 0; index < ARRAY_SIZE; index++)
{
inFile >> idArray[index];
}
inFile.close();
// BALANCE ARRAY
inFile.open(inFileName.c_str());
for(int index = 0; index < ARRAY_SIZE; index++)
{
inFile >> balanceArray[index];
}
inFile.close();
return outFileName;
}
#endif /* IOFUNCTIONS_H_ */
All help is greatly appreciated. If I'm missing anything, please let me know.
ReadInData takes a string*, but you are passing it a string. Fix this by passing a reference:
string ReadInData(string &nameArray, //<--
int idArray[],
float balanceArray[],
const int ARRAY_SIZE)