qs on to read numbers from a file

ok so I have three numbers in a file called input.dat and im able to call them but I want to know how to get those three numbers in that function and able to use them in other functions.

this is what I have any help appreciated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

double openFile()
{
  int num1=0;
  int num2=0;
  int num3=0;
  int numTotal=0;
  ifstream fin;
  fin.open("input.dat");
  if(fin.fail())
    {
      cout<<"error"<<endl;
      return -1.0;
    }
  fin>>num1>>num2>>num3;
  fin.close();
  cout<<"the numbers are:"<<num1<<" "<<num2<<" "<<num3<<endl;

  return 0;
}

 
This may be a dumb dumb way but hey, yolo.

This uses the stdio header file, and this is just an idea, not an answer
It gets a* number

numbers.txt
1 is kofi

code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <iostream>


int main(int argc, char * argv[]){
  int x = 0;
  FILE * pFile;
  pFile = fopen("numbers.txt", "r");
  if (pFile){
  
    fscanf(pFile, "%d+", &x);
    
  
    fclose(pFile);
  
    std::cout << x << std::endl;//yes I could have used printf, but again, yolo
  //printf("%d", x);
  }
}
  


output
>> 1


You could use what your os provided(like windows (win32) filesysteming thingy magigy)
Last edited on
have you tried stringstream(yourstring)>>xnumberhere?
ok I got it to work but now I want to have it to where the file can only read 3 lines of data I got it to work but I keep getting my error message to display when I already have my three numbers in the file any help would be appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void openFile(ifstream&fin,int &numA, int &numB, int &numC)
{
  fin.open("input.dat");

   if(fin.fail())
   {
   cout<<"error"<<endl;
   }
  fin>>numA>>numB>>numC;
  fin.close();

}
int readFile(ifstream&fin,int &numA, int &numB, int &num3)
{
  int count=0;

    while(!fin.eof())
   {
    fin >> numA;
    count++;
   }

  if(count < 3 || count >=4)
    {
      cout << "Error file doesn't have 3 lines of data" << endl;
      exit(1);
    }
  cout<<"The numbers in the file are "<<numA<<" "<<numB<<" "<<numC;
return 0;
}
Last edited on
Topic archived. No new replies allowed.