stream problem

V

vsgdp

Hello,

I'm wondering why this outputs garbage:

std::eek:fstream outFile("test.txt");

outFile << 1.0f << std::endl;
outFile << filename << std::endl;
outFile << 2.0f << std::endl;
std::string s;
float x;
std::ifstream inFile("test.txt");
inFile >> x;
std::cout << x << std::endl;
std::getline(inFile, s, '\n');
std::cout << s << std::endl;
inFile >> x;
std::cout << x << std::endl;

and why this works:

outFile << filename << std::endl;
outFile << 1.0f << std::endl;
outFile << 2.0f << std::endl;
std::string s;
float x;
std::ifstream inFile("test.txt");
std::getline(inFile, s, '\n');
std::cout << s << std::endl;
inFile >> x;
std::cout << x << std::endl;
inFile >> x;
std::cout << x << std::endl;

I think the former doesn't work because the getline() is reading the same
line as the previous inFile >> read. How can I get it to skip to the next
line, if that is indeed the problem.
 
J

John Harrison

vsgdp said:
Hello,

I'm wondering why this outputs garbage:

std::eek:fstream outFile("test.txt");

outFile << 1.0f << std::endl;
outFile << filename << std::endl;
outFile << 2.0f << std::endl;
std::string s;
float x;
std::ifstream inFile("test.txt");
inFile >> x;
std::cout << x << std::endl;
std::getline(inFile, s, '\n');
std::cout << s << std::endl;
inFile >> x;
std::cout << x << std::endl;

and why this works:

outFile << filename << std::endl;
outFile << 1.0f << std::endl;
outFile << 2.0f << std::endl;
std::string s;
float x;
std::ifstream inFile("test.txt");
std::getline(inFile, s, '\n');
std::cout << s << std::endl;
inFile >> x;
std::cout << x << std::endl;
inFile >> x;
std::cout << x << std::endl;

I think the former doesn't work because the getline() is reading the same
line as the previous inFile >> read.

Not quite.

getline is doing what it is supposed to which is reading up to the next
newline. Your mistake is thinking that inFile >> x will read a newline, but
it doesn't. inFile >> x reads a number and a newline is not part of a
number. So when you have a number followed by a newline the newline is left
behind unread. Then getline comes along and reads it.
How can I get it to skip to the next
line, if that is indeed the problem.

Use getline twice?

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top