read and print text file, from row to column

I have a text file containing numbers seperated by spaces. The numbers are written in rows. I want C++ to read the numbers and print them in a single column, i.e.
from "input.txt": 1.1 2.2 3.3
to:
1.1
2.2
3.3

So far I can only print the numbers in a row with the code below. Thank you very much. Kind regards, Chris

#include <fstream>
#include <iostream>

int main()
{
float input;

//Open file
std::ifstream inFile;
inFile.open("input.txt");

while(!inFile.eof())
{
//Get input
inFile >> input;

//Print input
std::cout << input;
}

//Close file
inFile.close();

return 0;
}
Use std::cout << std::endl; to print a newline.
Last edited on
Thank you very much! It works fine. Only problem is that the last number given in "input.txt" appears twice in the output. I will try to fix this. The adapted code is given below. Thanks! Cheers, Chris.

#include <fstream>
#include <iostream>

int main()
{
float input;

//Open file
std::ifstream inFile;
inFile.open("input.txt");

while(!inFile.eof())
{
//Get input
inFile >> input;

//Print input
std::cout << input << std::endl;
}

//Close file
inFile.close();

return 0;
}
Thanks! The now perfectly working code is given below. Thank you very much for your help! With kind regards, Chris.

PS: I also reduced "std::cout << input << std::endl;" to "std::cout << input << "\n";".

#include <fstream>
#include <iostream>

int main()
{
float input;

//Open file
std::ifstream inFile;
inFile.open("input.txt");

while (true)
{
//Get input
inFile >> input;

//Avoid repetition of last line:
if(inFile.eof() ) break;

//Print input
std::cout << input << "\n";

}

//Close file
inFile.close();

return 0;
}

Topic archived. No new replies allowed.