1

So I have a input file which contains several different integer values(each in a seperate line), now I need to read each value, find the square root and get the output. The issue I am having is that my code only reads the first value from the input file. I have a feeling I am supposed to be using a loop to read each value seperately, so if someone can help me out it would be really appreciated.

float file_inp() //reads values from file and calculates the square root
{
    float y = 0;
    ifstream fin;
    fin.open("input.txt",ios::in);
    if (fin)
    {
        int x = 0;
        fin >> x;
        y=sqrt(x);
    }

    return y;
}

int main()
{
    float y = 0;
    cout << file_inp();

    system("Pause");
    return 0;
}
Rahul Kadukar
  • 858
  • 3
  • 15
  • 35

1 Answers1

0

The main problem is that you have a function that reads the file and returns one number.
No amount of looping can make that function produce more than one number.

Instead of one function that does all the work, it's often better to have functions that do a little bit of work and use them over and over.
It's also a good idea to separate I/O from data processing.

This the common "elementwise processing of whitespace-separated input" loop:

int main()
{
    std::ifstream input("input.txt");  // No 'ios::in'; it's already an input stream.
    SomeType piece;
    while (input >> piece) // Read until you can't read no more.
    {
        process(piece);  // Do whatever you want to do.
    }
}

Adjust types and processing as necessary.

In your case,

int main()
{
    std::ifstream input("input.txt");
    int x;
    while (input >> x)
    {
        std::cout << std::sqrt(x) << std::endl;
    }
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82