Click here to Skip to main content
15,879,095 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
lets suppose in file we have,
6
3
4
8
1
9
13

Tell me how to read it from file and store these numbers in an array.

//First try
C++
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<fstream>
using namespace std;
char keys[25];
int main()
{
   

int count=0;
string data;
char k[20];
ifstream my("keys.txt");
//if (myfile.is_open())
//{
while (! my.eof() )
{

getline(my,data);
k[count]=data;
cout << data << endl;
count++;
}
my.close();
//size=data.length();
//cout<<"Length of string is : "<<size<<endl;
cout<<"The number of keys are :"<<count<<endl;
for(int i=0;i<count;i++)>
{
k[i]=data[i];
cout<<k[i];
}
/*for(int j=0;j!='\0';j++)
{
k[j]=data[j];        

}
for(int i=0;i!='\0';i++)
{
cout<<k[i];
cout<<endl;
}
//}
//else cout << "Unable to open file";


for(int j=0;j<size;j++)>
{
keys[j]=data[j];        

}
*/
system("pause");
return 0;

}


/////////////////////////////////////////////////
Second Prog

C++
#include<iostream>
//#include<stdio.h>
//#include<stdlib.h>
#include<conio.h>
using namespace std;

int main()
{
FILE *k;
int v;
k=fopen("pre1.c","r");
while(v=getc( k )!=EOF)
{
putch(v);
cout<<"Value is :"<<v<<endl;
}    
fclose(k);
system("pause");
return 0;
}
Posted
Updated 9-Dec-12 4:21am
v3
Comments
CHill60 9-Dec-12 8:37am    
Can you post what you've done so far. We'll help if we can but we're not here to do your homework for you :-)


  1. Read the next line from the file.
  2. Parse the line to see if it is a valid numeric string, and display a message if not.
  3. Convert the string to an integer.
  4. Store the integer to the array
  5. Repeat until no more data
 
Share this answer
 
Comments
[no name] 10-Dec-12 1:42am    
Good way of answering..My vote is 5
Richard MacCutchan 10-Dec-12 3:50am    
Thank you but this is the sort of basic information that should be learnt in the introduction to programming sections of the study courses.
C#
#include<stdio.h>
int main()
{
    freopen("input.txt","r",stdin);
   //freopen("output.txt","w",stdout);
    int  c,i=0;
    int array[100];
        while((scanf("%d",&c))!=EOF)
        {
            array[i++]=c;

        }
        //getchar();
        return 0;
}
 
Share this answer
 
v2
Google[^]

First search result: Input/Output with files[^]

std::string myString = "99";
int value = atoi(myString.c_str()); 


Best regards
Espen Harlinn
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900