Link to home
Start Free TrialLog in
Avatar of ifrit375
ifrit375

asked on

File input/output in C++

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?


Avatar of DarthNemesis
DarthNemesis

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
    }
}
Avatar of ifrit375

ASKER

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?
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.
If you're using fairly large numbers you might want to change the vector type to vector<long>.
Your method only works with interger less than or equal to 10, if it's greater than 10 it display different number.
The maximum number I use is 11111111111, I used long but still wouldn't display it:(
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?
ignore my last question.
>> 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);
>> 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);
Thanks for that it works:) But it come up with 4 warning, I'm not sure if you get it also.
I fixed the warning, thanks for your help.
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?
I fixed the warning, thanks for your help.
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
This only happens for the first time of compiling for some reason.
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];
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];
ASKER CERTIFIED SOLUTION
Avatar of DarthNemesis
DarthNemesis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> And instead of #include "varibles.cpp" put #include "variables.h".

Include that header in your main file and in display.cpp.
Thanks for the tip.
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
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