swscanf return wrong result - unicode

i use embarcadero Xe7. I found that swscanf returns wrong result.
example
int _tmain(int argc, _TCHAR* argv[])
{
char *t1= " ";
wchar_t *t2= L" ";
int i1, i2;
i1= -1;
i1= sscanf (t1, "%d", &i2);
if(i1!=EOF)
printf("sscanf output i1=%d i2=%d\n", i1, i2);
else
printf("sscanf EOF\n");
i1= swscanf(t2, L"%d", &i2);
if(i1!=EOF)
printf("swscanf output i1=%d i2=%d\n", i1, i2);
else
printf("swscanf EOF\n");
return 0;
}
the result:
sscanf EOF
swscanf output i1=1 i2=0
The first result is ok. But the second is wrong.

This is a bug. This behaviour of swscanf() contradicts the C11 standard:
7.29.2.4/3 The swscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has
completed. Otherwise, the swscanf function returns the number of input
items assigned, which can be fewer than provided for, or even zero, in
the event of an early matching failure.
Clearly, here it fails before the first conversion has started.
It also contradicts the XE7 sscanf/swscanf documentation:
If sscanf attempts to read at end-of-string, it returns EOF.
And again, clearly, here it attempts to read end of string.
There is no bug report for now on EDN. You should file one.
*Workaround: process the cases i1==EOF and i1==0 together, as in both cases you can't exploit the content of any variable.

Related

Systemverilog expansion rule

When I review some codes, I found something strange.
It seems that it comes from expansion and operation priority.
(I know that because "sig" is declared with 'signed', $signed is not necessary and '-sig' is correct one, anyway..)
reg signed [9:0] sig;
reg signed [11:0] out;
initial
begin
$monitor ("%0t] sig=%0d, out=%0h", $time, sig, out);
sig = 64;
out = $signed(-sig);
#1
out = -$signed(sig);
#1
sig = -512;
out = $signed(-sig);
#1
out = -$signed(sig);
#1
$finish;
end
Simulation result for above codes is,
0] sig=64, out=-64
2] sig=-512, out=-512
3] sig=-512, out=512
When sig=-512, I expected that 10 bits sig would be expanded to 12bits before negation, but it was expanded after negation.
Therefore negation of -512 was still -512, and after expansion, it had a -512.
I guess "$signed() blocks expansion..Any idea what happens??
First of all, -512 and 512 are identical numbers in 10-bit represenntation. 10 bits can actually only hold signed values from -512 to 511. In this scheme negation of -512 should work weirdly, not mentioned in lrm, at least i was not able to locate anything related. This is probably an undefined behavior.
However, it is logical to assume that in this scheme in order to represent a negated value of '-512' just removing signess is sufficient. It seems that all commercial compilers in eda playground do this. So, a result of the unaray - operator in this case will be unsigned value of 512.
So, in out = $signed(-(-512)) the negation operator returns an unsigned value of 512 and it gets converted to a signed by the system task. Therefore, it gets sign extended in out.
out = -$signed(-512) for the same reason the outermost negation operator returns an unsigned value of 512. No sign extension happens here.
You can again make it signed by enclosing in yet another $signed as out = $signed(-$signed(-512))

When can TLM peek fail?

I was working on OVM driver sequencer communication. I am using try_get_item() in ovm driver but it is still getting stuck. In my sequencer I redefined try_next_item and just printed a display statement before and after m_req_fifo.peek(t); The statement before peek got executed but not the statement after the peek. I even displayed size of the m_req_fifo using m_req_fifo.size() and it printed out 1. Why is peek not returning anything even after the size is 1? The modified try_next_item (Just addition of display) is given below.
The line After PEEK never gets executed after the line Line 398 with fifo size 1
virtual task try_next_item(output REQ t);
int selected_sequence;
time arb_time;
ovm_sequence_base seq;
if (get_next_item_called == 1) begin
ovm_report_error(get_full_name(), "get_next_item/try_next_item called twice without item_done or get in between", OVM_NONE);
return;
end
wait_for_sequences();
selected_sequence = choose_next_request();
if (selected_sequence == -1) begin
t = null;
return;
end
set_arbitration_completed(arb_sequence_q[selected_sequence].request_id);
seq = arb_sequence_q[selected_sequence].sequence_ptr;
arb_sequence_q.delete(selected_sequence);
m_update_lists();
sequence_item_requested = 1;
get_next_item_called = 1;
$display("Line 398 with fifo size %0d\n", m_req_fifo.size());
m_req_fifo.peek(t);
$display("After PEEK\n");
wait_for_sequences();
// attempt to get the item; if it fails, produce an error and return
if (!m_req_fifo.try_peek(t))
ovm_report_error("TRY_NEXT_BLOCKED", {"try_next_item: the selected sequence '",
seq.get_full_name(), "' did not produce an item during wait_for_sequences(). ",
"Sequences should not consume time between calls to start_item and finish_item. ",
"Returning null item."}, OVM_NONE);
endtask
uvm_tlm_fifo::size() doesn't return the number of elements in the FIFO, but its capacity (i.e. the maximum number of elements it can hold). The function you're looking for is uvm_tlm_fifo::used() which returns the number of stored elements.
The function names are not intuitive at all and I remember spending a couple of hourse trying to understand some similar code to the one you had until noticing in the documentation that I was using the wrong method.

Comparing Decimals (not floats) in Swift

I have a test case with the following line:
XCTAssert(testVal == value)
value and testVal are both Decimals. In most cases the equivalence test gives the expected result, but not always. For instance
let value = Decimal(0xFFFF)
... do stuff that generates testVal
XCTAssert(testVal == value) // evaluates false
BUT, when I look at value and testVal, they appear to be the same.
(lldb) print testVal == value
(Bool) $R0 = false // the condition causing the test to fail
(lldb) print value.description
(String) $R1 = "65535" // what you would expect, given the init
(lldb) print testVal.description
(String) $R2 = "65535" // the same as value. Hmmm...
(lldb) print (testVal - value).isZero
(Bool) $R3 = true // the difference is zero, but they are not equal?
I checked all the attributes of the two Decimals and even the hash values are the same, yet they evaluate to not being equal. The only difference I see is that one is compact and the other is not. I don't see a way to force compaction, so I don't know if this is a factor.
When initializing with other values, like 0xFF, 65535.1, and a host of others, the tests compare successfully.
While this sort of behavior is typical of floats, it should not happen for Decimals, should it?
OK, found the answer not long after posting this: It does have to do with the Decimal being compacted. From the docs:
All the NSDecimal... arithmetic functions expect compact NSDecimal arguments.
Once I added the line
NSDecimalCompact(&testVal)
The comparisons worked as expected.

1mpl3m3nt vector stack & output a stored&counted item

Here's my code:
I currently have everything the user enters dumped into the stack and sorted, but I don't how/where to go from here. I tried solving it with a count variable, but my solution isn't proper (it should output "2 dog" only once if the user enters dog twice). If anybody can help or knows a way to solve this, please give an example.
There are multiple ways to do this. The easiest is a simple use of std::map:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, unsigned int> mymap;
std::string s;
while (std::getline(std::cin, s) && !s.empty() && s != "END")
++mymap[s];
for (auto const& pr : mymap)
std::cout << pr.second << ':' << pr.first << '\n';
}
How it works
Each line is read, and if successful (not eof, not empty, and not equivalent to "END") is used for updating an entry in the map.
Per the documentation for std::map::operator [], if the requisite key is not already present in the map, it is added, and mapped-to value is value-initialized. For unsigned int that means the initial value is 0.
From there, the increment is applied to the returned unsigned int reference, which for a new element, results in the value 1, for existing elements, it simply increments the prior value.
This continues until the loop terminates.
Upon termination of the loop the results are reported in lexicographical order, preceded by their count.
Input
one
two
three
four
three
one
one
one
two
END
Output
1:four
4:one
2:three
2:two
If you wanted to sort the output based on count, more work would need to be done, but it isn't difficult. A set of pairs from the map, inverted so the count is first, the string second, makes short work of that:
#include <iostream>
#include <string>
#include <map>
#include <set>
int main()
{
std::map<std::string, unsigned int> mymap;
std::string s;
while (std::getline(std::cin, s) && !s.empty() && s != "END")
++mymap[s];
std::set<std::pair<unsigned int, std::string>> ms;
for (auto const& pr : mymap)
ms.insert(std::make_pair(pr.second, pr.first));
for (auto const& pr : ms)
std::cout << pr.first << ':' << pr.second << '\n';
}
An example run appears below:
Input
one
two
three
four
three
one
one
one
two
END
Output
1:four
2:three
2:two
4:one
Use std::map as mentioned in comment:
std::map<std::string, unsigned int> countMap;
while(enter!=endString){
getline(cin,enter);
countMap[enter]++; // Operator `[]` enters a new key if not present and
// default initializes the value.
//, else fetches and increases the corresponding value
}
// coutMap[str] gives the number of times `str` entered.
You should use map. But if you are searching for another answer, use a search over all elements.
after you read all elements from input, start looping over vector. get first element, store its value and remove it then check other size-1 elements to see if they are equal to this one. if yes, add counter and remove the item from vector.
Notice that size has decreased. now again do the same till size becomes 0.

Result of an assignment in Java

I am looking at the code on page 11 here http://www.cs.usfca.edu/~parrt/doc/java/JavaIO-notes.pdf
I have trouble with one statement. I thought the result of an assignment was an lvalue. So ((byteRead = inFile.read()) != -1) should be the same as (inFile.read()) != -1). This doesn't seem to be the case though looking at the output. So my question is how is the statement ((byteRead = inFile.read()) != -1) parsed?
EDIT: It seems from the responses that I had the current interpretation of the result of an assignment. I was wondering what goes wrong by replacing the code fragment
int byteRead;
while((byteRead = inFile.read()) != -1)
outFile.write(byteRead);
with
while( inFile.read() != -1)
outFile.write( inFile.read());
So, now that you posted both versions of code, the answer is clear:
In your first version, each byte read is assigned to byteRead and then written to the output stream.
In the second version, you consume a byte with the read() but don't assign it to a variable. Then, you read another byte (the next one in the stream) which you write to the output stream.
So, if the input file is:
abcdefghijklmnopqrstuvwxyz
The output of the first version will be :
abcdefghijklmnopqrstuvwxyz
The output of the second will be :
bdfhjlnqrtuxz
((byteRead = inFile.read()) != -1) and (inFile.read() != -1) are, in one sense, equivalent boolean expressions. However, the first one has a side effect: It stores the result of inFile.read() in the variable byteRead.
The code example you referenced uses this for a compact while loop that reads one byte from input, writes it to output and keeps doing that until inFile.read() returns -1 (meaning end of file has been reached).