?
Solved

File input/output in C++

Posted on 2003-03-21
24
Medium Priority
?
409 Views
Last Modified: 2010-04-01
Ok, I'm writing a basic program that store a set of numbers in a file with the following code:

#include<fstream>
#include<iostream>
#include<string>

using namespace std;

char fileName[20];
int num;
char ch;
string test;


void storeFile()
{
     cout<<"Enter the name of the new file:";
     cin>>fileName;
     cout<<"\nEnter the number you wish to store:";
     cin>>num;

     ofstream file;
     file.open(fileName, ios_base::out|ios_base::app);

     file<<num<<endl;

     file.close();
}

What my question how do I read the file line by line? Like if I have 5 set of input how would I be able to read what line I want, e.g. line 5?


0
Comment
Question by:ifrit375
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
24 Comments
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8185189
Unless you know the offset of the number you stored (which isn't likely if you store numbers with different amounts of digits), you'll have to read through the file sequentially. However, if you store the numbers in an array, you only have to do this once.

#include<fstream>
#include<iostream>
#include<string>
#include<vector>

using namespace std;

vector<int> Numbers;

void ReadFile() {
    string fileNameStr;
    string readStr;
    cout<<"Enter the name of the file to open: ";
    getline(cin, fileNameStr);

    ifstream file;
    file.open(fileNameStr.c_str());

    Numbers.clear();

    while (!file.eof()) {
         getline(file, readStr);
         Numbers.push_back(atoi(readStr.c_str()));
    }

    file.close();
}

void main() {
    ReadFile();
    for (int i=0; i<Numbers.size(); i++) {
        cout << Numbers[i] << endl; // Numbers[n-1] will hold the number from line n
    }
}
0
 

Author Comment

by:ifrit375
ID: 8185426
But how would I just pick what line I want to view, e.g.
I have the following text in a file:

line1: 1212323
line2: 1212232131
line3: 231289321

How would I tell the program just to display line3?
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8185443
That's what I meant by // Numbers[n-1] will hold the number from line n.

The line:

cout << Numbers[2] << endl;

Will display line 3.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8185463
If you're using fairly large numbers you might want to change the vector type to vector<long>.
0
 

Author Comment

by:ifrit375
ID: 8185596
Your method only works with interger less than or equal to 10, if it's greater than 10 it display different number.
0
 

Author Comment

by:ifrit375
ID: 8185605
The maximum number I use is 11111111111, I used long but still wouldn't display it:(
0
 

Author Comment

by:ifrit375
ID: 8185610
But how would I just pick what line I want to view, e.g.
I have the following text in a file:

line1: 1212323
line2: 1212232131
line3: 231289321

How would I tell the program just to display line3?
0
 

Author Comment

by:ifrit375
ID: 8185612
ignore my last question.
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8185623
>> Your method only works with interger less than or equal to 10, if it's greater than 10 it display different number.

That doesn't happen for me...

>> The maximum number I use is 11111111111, I used long but still wouldn't display it:(

If you _just_ want to display the number as text and not mess with the value, a solution would be to store it as a string. You would have to change vector<long> Numbers; to vector<string> Numbers; and Numbers.push_back(atol(readStr.c_str())); to Numbers.push_back(readStr);
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8185625
>> Your method only works with interger less than or equal to 10, if it's greater than 10 it display different number.

That doesn't happen for me...

>> The maximum number I use is 11111111111, I used long but still wouldn't display it:(

If you _just_ want to display the number as text and not mess with the value, a solution would be to store it as a string. You would have to change vector<long> Numbers; to vector<string> Numbers; and Numbers.push_back(atol(readStr.c_str())); to Numbers.push_back(readStr);
0
 

Author Comment

by:ifrit375
ID: 8185626
Thanks for that it works:) But it come up with 4 warning, I'm not sure if you get it also.
0
 

Author Comment

by:ifrit375
ID: 8185629
I fixed the warning, thanks for your help.
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8185631
I get one warning "Comparing signed and unsigned values" because the loop is initialized with int i instead of unsigned int i. Which ones do you get?
0
 

Author Comment

by:ifrit375
ID: 8185636
I fixed the warning, thanks for your help.
0
 

Author Comment

by:ifrit375
ID: 8185645
c:\program files\microsoft visual studio\vc98\include\vector(39) : warning C4786: 'std::reverse_iterator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > const *,std::basic_string<char,std::char_traits<char>,std::allocator<char>
>,std::basic_string<char,std::char_traits<char>,std::allocator<char> > const &,std::basic_string<char,std::char_traits<char>,std::allocator<char> > const *,int>' : identifier was truncated to '255' characters in the debug information
        c:\program files\microsoft visual studio\vc98\include\vector(39) : while compiling class-template member function '__thiscall std::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<c
har,std::char_traits<char>,std::allocator<char> > > >::std::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > >(const std::allocator<std:
:basic_string<char,std::char_traits<char>,std::allocator<char> > > &)'
c:\program files\microsoft visual studio\vc98\include\vector(39) : warning C4786: 'std::reverse_iterator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > *,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std:
:basic_string<char,std::char_traits<char>,std::allocator<char> > &,std::basic_string<char,std::char_traits<char>,std::allocator<char> > *,int>' : identifier was truncated to '255' characters in the debug information
        c:\program files\microsoft visual studio\vc98\include\vector(39) : while compiling class-template member function '__thiscall std::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<c
har,std::char_traits<char>,std::allocator<char> > > >::std::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > >(const std::allocator<std:
:basic_string<char,std::char_traits<char>,std::allocator<char> > > &)'
c:\program files\microsoft visual studio\vc98\include\vector(39) : warning C4786: 'std::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > >
 >::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > >' : identifier was truncated to '255' characters in the debug information
c:\program files\microsoft visual studio\vc98\include\vector(60) : warning C4786: 'std::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > >
 >::~vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > >' : identifier was truncated to '255' characters in the debug information

This is what I get
0
 

Author Comment

by:ifrit375
ID: 8185646
This only happens for the first time of compiling for some reason.
0
 

Author Comment

by:ifrit375
ID: 8185650
Here is my full code used:
#define varibles_h
#ifndef varibles_h
#include "varibles.cpp"
#endif;      

#include"display.cpp"
#include"validation.cpp"

void main()
{
      do
      {
            cout<<"Enter input:";
            getline(cin, input);
            cin.get();

            if(input.length()>15)
            {
                  system("cls");
                  cout<<"Your input is too large, input must be less than 16. Please try again\n";
            }
      }while(input.length()>15);

      display();
}
      
display.cpp:
#include "varibles.cpp"
#include <vector>


vector<string> Numbers;

void heading()
{
      cout<<setw(54)<<"Binary Bits"<<endl;
      cout<<setw(10)<<"Char"<<setw(23)<<"P1"<<setw(4)<<"P2"<<setw(4)<<"64"<<setw(4)<<"P4"<<setw(4)<<"32"<<setw(4)<<"16"<<setw(3)<<"8"<<setw(4)<<"P8"<<setw(3)<<"4"<<setw(3)<<"2"<<setw(3)<<"1"<<endl;
}

void line()
{
      for(int m=0;m<75;m++)
      {
            cout<<"=";
      }
      cout<<endl;
}

void int_to_binary()
{
      do
      {
            for(int i=6; i>-1; i--)
            {
                  binary[i]=num%2;
                  num=num/2;
            }
      }while(num/2 !=0);
}

void transmission_bit()
{      
      cout<<setw(23)<<parity_bits[0];
      cout<<setw(4)<<parity_bits[1];
      cout<<setw(4)<<binary[0];
      cout<<setw(4)<<parity_bits[2];
      cout<<setw(4)<<binary[1];
      cout<<setw(4)<<binary[2];
      cout<<setw(4)<<binary[3];
      cout<<setw(4)<<parity_bits[3];
      cout<<setw(3)<<binary[4];
      cout<<setw(3)<<binary[5];
      cout<<setw(3)<<binary[6];

      ofstream file;
      file.open("wang", ios_base::out|ios_base::app);

      file<<parity_bits[0]<<parity_bits[1]<<binary[0]<<parity_bits[2]<<binary[1]<<binary[2]<<binary[3]<<parity_bits[3]<<binary[4]<<binary[5]<<binary[6]<<endl;
      file.close();
}

void make_error()
{
      string fileName="wang";
      string readStr;

      ifstream file;
      file.open(fileName.c_str());

      Numbers.clear();

      while (!file.eof())
      {
            getline(file, readStr);
            Numbers.push_back(readStr);
      }

      file.close();
}

int random_number()
{
      random_integer = (rand()%input.length())+1;
      return random_integer;
}

void parity_bits_test()
{
      for(int check=0; check<4; check++)
      {
            switch(check)
            {
                  case 0: if(((binary[0]+binary[1]+binary[3]+binary[4]+binary[6])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[0]+binary[1]+binary[3]+binary[4]+binary[6])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;

                  case 1: if(((binary[0]+binary[2]+binary[3]+binary[5]+binary[6])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[0]+binary[2]+binary[3]+binary[5]+binary[6])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;

                  case 2: if(((binary[1]+binary[2]+binary[3])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[1]+binary[2]+binary[3])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;

                  case 3: if(((binary[4]+binary[5]+binary[6])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[4]+binary[5]+binary[6])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;
            }
      }
}


void display()
{
      system("cls");
      length=input.length();
      heading();
      line();

      for(int i=0; i<length; i++)
      {
            letter=input.at(i);
            num=letter;
            cout<<setw(9)<<input.at(i);
                              
            int_to_binary();      
            parity_bits_test();
            transmission_bit();
            cout<<endl;
      }
      cout<<"\nTransmitting above code.\n";
      system("pause");

      srand((unsigned)time(0));//Seed the generator with the system time then output a single random number, which should be different each time we run the program.
      for(int times=0; times<5; times++)      
      {
            make_error();
            error_binary[times]=Numbers[(random_number())-1];
      }
}


varible.cpp:
#include<iostream>
#include<string>
#include<iomanip>
#include <cstdlib>
#include<ctime>
#include<fstream>


using namespace std;
      
      string input;
      int num;
      int length;
      char letter;
      int binary[7];
      int parity_bits[4];
      string evenOdd;
      int random_integer;
      string error_binary[5];
0
 

Author Comment

by:ifrit375
ID: 8185666
Here is my full code used:
#define varibles_h
#ifndef varibles_h
#include "varibles.cpp"
#endif;      

#include"display.cpp"
#include"validation.cpp"

void main()
{
      do
      {
            cout<<"Enter input:";
            getline(cin, input);
            cin.get();

            if(input.length()>15)
            {
                  system("cls");
                  cout<<"Your input is too large, input must be less than 16. Please try again\n";
            }
      }while(input.length()>15);

      display();
}
      
display.cpp:
#include "varibles.cpp"
#include <vector>


vector<string> Numbers;

void heading()
{
      cout<<setw(54)<<"Binary Bits"<<endl;
      cout<<setw(10)<<"Char"<<setw(23)<<"P1"<<setw(4)<<"P2"<<setw(4)<<"64"<<setw(4)<<"P4"<<setw(4)<<"32"<<setw(4)<<"16"<<setw(3)<<"8"<<setw(4)<<"P8"<<setw(3)<<"4"<<setw(3)<<"2"<<setw(3)<<"1"<<endl;
}

void line()
{
      for(int m=0;m<75;m++)
      {
            cout<<"=";
      }
      cout<<endl;
}

void int_to_binary()
{
      do
      {
            for(int i=6; i>-1; i--)
            {
                  binary[i]=num%2;
                  num=num/2;
            }
      }while(num/2 !=0);
}

void transmission_bit()
{      
      cout<<setw(23)<<parity_bits[0];
      cout<<setw(4)<<parity_bits[1];
      cout<<setw(4)<<binary[0];
      cout<<setw(4)<<parity_bits[2];
      cout<<setw(4)<<binary[1];
      cout<<setw(4)<<binary[2];
      cout<<setw(4)<<binary[3];
      cout<<setw(4)<<parity_bits[3];
      cout<<setw(3)<<binary[4];
      cout<<setw(3)<<binary[5];
      cout<<setw(3)<<binary[6];

      ofstream file;
      file.open("wang", ios_base::out|ios_base::app);

      file<<parity_bits[0]<<parity_bits[1]<<binary[0]<<parity_bits[2]<<binary[1]<<binary[2]<<binary[3]<<parity_bits[3]<<binary[4]<<binary[5]<<binary[6]<<endl;
      file.close();
}

void make_error()
{
      string fileName="wang";
      string readStr;

      ifstream file;
      file.open(fileName.c_str());

      Numbers.clear();

      while (!file.eof())
      {
            getline(file, readStr);
            Numbers.push_back(readStr);
      }

      file.close();
}

int random_number()
{
      random_integer = (rand()%input.length())+1;
      return random_integer;
}

void parity_bits_test()
{
      for(int check=0; check<4; check++)
      {
            switch(check)
            {
                  case 0: if(((binary[0]+binary[1]+binary[3]+binary[4]+binary[6])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[0]+binary[1]+binary[3]+binary[4]+binary[6])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;

                  case 1: if(((binary[0]+binary[2]+binary[3]+binary[5]+binary[6])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[0]+binary[2]+binary[3]+binary[5]+binary[6])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;

                  case 2: if(((binary[1]+binary[2]+binary[3])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[1]+binary[2]+binary[3])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;

                  case 3: if(((binary[4]+binary[5]+binary[6])%2)==0)
                              {
                                    parity_bits[check]=0;
                              }
                              else if(((binary[4]+binary[5]+binary[6])%2)!=0)
                              {
                                    parity_bits[check]=1;
                              }
                              break;
            }
      }
}


void display()
{
      system("cls");
      length=input.length();
      heading();
      line();

      for(int i=0; i<length; i++)
      {
            letter=input.at(i);
            num=letter;
            cout<<setw(9)<<input.at(i);
                              
            int_to_binary();      
            parity_bits_test();
            transmission_bit();
            cout<<endl;
      }
      cout<<"\nTransmitting above code.\n";
      system("pause");

      srand((unsigned)time(0));//Seed the generator with the system time then output a single random number, which should be different each time we run the program.
      for(int times=0; times<5; times++)      
      {
            make_error();
            error_binary[times]=Numbers[(random_number())-1];
      }
}


varible.cpp:
#include<iostream>
#include<string>
#include<iomanip>
#include <cstdlib>
#include<ctime>
#include<fstream>


using namespace std;
      
      string input;
      int num;
      int length;
      char letter;
      int binary[7];
      int parity_bits[4];
      string evenOdd;
      int random_integer;
      string error_binary[5];
0
 
LVL 2

Accepted Solution

by:
DarthNemesis earned 200 total points
ID: 8185684
Create a file variables.h with the following:

#ifndef variables_h
#define variables_h

#include "variables.cpp"
#endif

And instead of #include "varibles.cpp" put #include "variables.h". The ndef/define directives are used in order to prevent the file from being included twice - the first time it's included, variables_h is not defined, so the code is included. Any subsequent times variables.h is included variables_h is defined, so the entire file is skipped over.
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8185686
>> And instead of #include "varibles.cpp" put #include "variables.h".

Include that header in your main file and in display.cpp.
0
 

Author Comment

by:ifrit375
ID: 8185746
Thanks for the tip.
0
 
LVL 8

Expert Comment

by:fl0yd
ID: 8185946
ifrit375: "This only happens for the first time of compiling for some reason."

Wrong. It happens each and every time the translation unit is compiled in debug mode with vc++ <= 6.0. As for the 'some reason', can't you just read it?? Compiler writers try to make warning/error descriptions as informative as possible. If you are still in doubt what it means, place the cursor over the warning number on press F1. The warning C4786 indicates the the symbolic identifier is longer than 255 characters in length and has to be truncated, thus it will not be fully compiled into the executable and in return not fully displayed during debugging. The maximum length of 255 characters for identifiers isn't there anymore in vc++ 7.0. Oh well, the irony of the Information Age is that it has given new respectability to uninformed opinion...

.f
0
 
LVL 11

Expert Comment

by:bcladd
ID: 9543967
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Answered: Points to DarthNemesis

Please leave any comments here within the next seven days. Experts: Silence
means you don't care.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

-bcl (bcladd)
EE Cleanup Volunteer
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question