Reading in one byte at a time with .get() [duplicate] - c++

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 7 years ago.
So i'm reading in a input file that contains:
lololololololol
I need to read it in using binary one byte at a time for something I'm doing later on. To do this i'm using get() to read it in then storing it into a char. It seems to be working correctly except for the last char that it reads in. The vector that it is reading into contains:
lololololololol
�
I'm not quite sure what this last value is but it's totally throwing off my finial output. So my question is, is there a reason get() would read in a value or byte from my text document that is not there? Or is it reading in something that I don't know of?
code:
while(istr.good()) {
temp = istr.get();
input.push_back(temp);
}

It's reading the EOF (end of file) character. You need to do the check after reading it to avoid it being inserted to the vector:
while(temp = istr.get(), istr.good()) // comma operator
input.push_back(temp);
Or you might use the 2nd std::istream_base::get overload and let istr implicitly convert to bool:
while(istr.get(temp))
input.push_back(temp);
Or try more advanced approaches. operator>> and std::getline would also work fine for this kind of input.

Related

Reading Line by Line in C++ for Pairs [duplicate]

This question already has answers here:
reading text with whitespaces in c++
(2 answers)
How to read the whole lines from a file (with spaces)?
(4 answers)
Closed 4 months ago.
I have an input file that looks something like this:
0.1 239.402
0.4. 32342.34
0.7 4.924939
and so on...
I am trying to read it line by line using the fstream extraction operator >>
I need a way to set a while loop condition that would stop at the end of the file, and I need a way to push the two as a pair onto two stacks
The stacks are previously implemented in a class file Stack as linked lists
I currently have something like
double a, double b
std::string t;
Stack av;
Stack bv;
while(i>>a>>t>>b&&(t=="\t"){
av.push(a);
bv.push(b);
}
i know i'm incorrect as it's not always a tab space gap. also the file starts with a couple of spaces until the first row and then has a random number of spaces until the second row, and then a next line.
Is there a way to write a program where it knows when there is a double to read and use the random number of whitespaces as separation between a and b?
I hope this makes sense! Thanks so much for your help as I'm a beginner.

What does ~(tilde) means before scanf function in c++? [duplicate]

This question already has answers here:
The tilde operator in C
(6 answers)
Closed 3 years ago.
I found a code that takes input string and print them out.
But I don't know what does the tilde means in front of the scanf.
I found tilde can be used for either destructor or binary negation but it doesn't look like both. And the code doesn't work without tilde.
int main() {
char arr;
while (~scanf("%c", &arr)){
putchar(arr);
}
}
I found tilde can be used for either destructor or binary negation but it doesn't look like both.
It's the bitwise NOT operator applied to the return value of scanf() as you mentioned latter.
And the code doesn't work without tilde.
As #Mukul Gupta explained in their comment:
scanf returns the number of values it scanned successfully or EOF
if it reaches the end of file. EOF is a macro that represents a
negative value. On most platforms, the value of EOF is (int) -1.
In this case, taking 1's complement of -1, will make the value as 0
and is used to break from the loop.

How to Duplicate a file pointer [duplicate]

This question already has answers here:
Duplicating file pointers?
(3 answers)
Closed 7 years ago.
I want to use fgets twice on the same stream. I have defined two file pointer pointing to the same file but when I use fgets on one of the pointer, the other also gets modified.
fun(FILE * input) {
FILE * input_dup=input;
char str[2];
fgets(str, 2, input);
fgets(str, 2, input_dup);
}
On the second call to fgets, why is it reading the next character.. It should give the same output as they both are pointing to the same location
Well, you are laboring under a fundamental mis-understanding:
If you copy a pointer, that does not copy the object it points to.
As it happens, there's no standard way for duplicating a FILE (though there are nonstandard ones, see: Duplicating file pointers?).
Which doesn't happen you are SOL, you can just use ftell to get the current position, and fseek to get back there (provided the stream is seekable, like a file).
As with all C++ coding, it is doing exactly what you told it to do. If you want another copy, you could make an overriding function that tells the system to read and act and copy the stream and return a pointer to an array. That would accomplish your goal.
Asecond solution would be to unget the stream's last char, then read again.

eof() is returning last character twice [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 7 years ago.
I am reading in from an input file "input.txt" which has the string 'ABCDEFGH' and I am reading it in char by char. I am doing this using the code:
ifstream plaintext (input.txt);
char ch;
if (plaintext.is_open())
{
while(!plaintext.eof()){
plaintext.get(ch);
cout<<ch<<endl;
}
plaintext.close();
}
The string 'ABCDEFGHH' is printed out. I have no idea why it is printing 'H' twice. Any help would be appreciated. I got this code example from HERE
This is because the EOF test does not mean "our crystal ball tells us that there are no more characters available in this tream". Rather, it is a test which we apply after an input operation fails to determine whether the input failed due to running out of data (EOF) or some other condition (an I/O error of some sort).
In other words, EOF can be false even after we have successfully read what will be the last character. We will then try to read again, and this time get will fail, and not overwrite the existing value of ch, so it still holds the H.
Streams cannot predict the end of the data because then they could not be used for communication devices such as serial lines, interactive terminals or network sockets. On a terminal, we cannot tell that the user has typed the last character they will ever type. On a network, we cannot tell that the byte we have just received is the last one. Rather, we know that the previous byte was the last one, because the current read operation has failed.

Why is (foobar>>x) preferred over (! foobar.eof() ) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?
eof() bad practice?
My teacher said we shouldn't use EOF to read in text file or binary file information instead we should use (afile>>x). He didn't explain why, can someone explain to me. Can someone also explain what are the differences in this two different method of reading
//Assuming declaration
//ifstream foobar
( ! foobar.eof() )
{
foobar>>x; // This is discouraged by my teacher
}
while (foobar>>x)
{
//This is encouraged by my teacher
}
Because the file is not at the end before you try to read from it.
operator>> returns a reference to the stream in the state it is after the read has been attempted and either succeeded or failed, and the stream evaluates to true if it succeeded or false if it failed. Testing for eof() first means that the file can have no useful data in it but not be at EOF yet, then when you read from it, it's at EOF and the read fails.
Another important detail is that operator>> for streams skips all leading whitespace, not trailing whitespace. This is why a file can not be at EOF before the read and be at EOF after a read.
Additionally, the former works when the next data in the file is data that cannot be read into an integer (for example, the next data is x), not just when it's at EOF, which is very important.
Example:
Consider the code:
int x, y;
f >> x;
if (!f.eof())
f >> y;
Assuming f is a file that contains the data 123␣ (the ␣ means space), the first read will succeed, but afterwards the file has no more integers in it and it is not at EOF. The second read will fail and the file will be at EOF, but you don't know because you tested for EOF before you tried reading. Then your code goes on to cause undefined behaviour because y is uninitialised.