|
No way pal. What I'm try to say is that, use of == style is more easy and more reliable as far as I know. That's why I use the same way also. Chen says that there can be an issue on == style against = style. So the only way to happened is mis-type of the code, isn't it?
I appreciate your help all the time...
Eranga
|
|
|
|
|
This is nonsense! There is nothing wrong with testing
if (c == '\n') {}
some folk suggest that you write:
if ('\n' == c) {}
as this results in an error if you type '=' instead of '==' but I find this hard to read so I use the first form. Most compilers will issue a warning for assignment in comparison operations these days.
I mentioned the isspace() function as when I see people testing for the whitespace characters it looks as if they don't know about it. It is much more efficient. If it is not what you need and you have to test for multiple characters, it is much more efficient to do:
switch (c)<br />
{<br />
case '\n':<br />
case '\r':<br />
case '\t':<br />
case ' ':<br />
..<br />
break;<br />
...<br />
}
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."
|
|
|
|
|
cp9876 wrote: If it is not what you need and you have to test for multiple characters, it is much more efficient to do:
switch (c)
{
case '\n':
case '\r':
case '\t':
case ' ':
..
break;
...
}
As general rule, yes. Anyway compilers are enough smart nowadays,
at least whenever optimization is turned on, as in VS Release Build:
if (myString[i] == '\n' || myString[i] == '\r' || myString[i] == '\t')
00401040 movzx ecx,word ptr string L"hello world" (4020F4h)[edx*2]
00401048 cmp cx,0Ah
0040104C je test003+4Ah (40105Ah)
0040104E cmp cx,0Dh
00401052 je test003+4Ah (40105Ah)
00401054 cmp cx,9
00401058 jne test003+4Dh (40105Dh)
{
count++;
0040105A add esi,1
}
switch(myString[i])
0040105D movzx ecx,cx
00401060 cmp ecx,9
00401063 jl test003+62h (401072h)
00401065 cmp ecx,0Ah
00401068 jle test003+5Fh (40106Fh)
0040106A cmp ecx,0Dh
0040106D jne test003+62h (401072h)
{
case '\n':
case '\r':
case '\t':
count++;
0040106F add esi,1
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
|
|
|
|
|
You are right, for a few cases the difference may be negligible.
My understanding is that the switch statement can be optimized to O(log(N)) operations (using a tree type of search), whereas the simple cascaded if's will be O(N) operations. Obviously these could be the same but the compiler knows it can optimize a switch statement as the cases are all integer constants. I'd be interested to know the results if anyone can be bothered to do some test cases and analyse the code. It may be that the way the case statements are tested using less than operations is indicative that it would use a tree search for more cases (instead of the simple comparisons in the if construct).
Typically for lexical analyzers there are many cases and this type of optimization can be important (even better to use the provided character classification functions like isspace())
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."
|
|
|
|
|
cp9876 wrote: You are right, for a few cases the difference may be negligible.
In fact there is no difference at all, in the code snippet shown.
cp9876 wrote: My understanding is that the switch statement can be optimized to O(log(N)) operations (using a tree type of search), whereas the simple cascaded if's will be O(N) operations. Obviously these could be the same but the compiler knows it can optimize a switch statement as the cases are all integer constants. I'd be interested to know the results if anyone can be bothered to do some test cases and analyse the code. It may be that the way the case statements are tested using less than operations is indicative that it would use a tree search for more cases (instead of the simple comparisons in the if construct).
OK, got the point.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
|
|
|
|
|
CPallini wrote: In fact there is no difference at all, in the code snippet shown
There is - and depending on the distribution of characters one will be better than the other. My suspicion is that on normal text that the case statement will perform very slightly worse. Note that in the if statement all three tests are always performed. In the case statement the compiler analyses the case values and provides a short-cut if the value is < 9 - all other testing is bypassed. It was a good try and it didn't know that the data was positive, so providing a shortcut if the value was > D would have provided significantly better performance.
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."
|
|
|
|
|
You're right. I missed the shortcut inside the switch statement.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
|
|
|
|
|
Even me believe == style is a good way, as I said all those things can be happened because of the wrong typing.
I have one question. I can use a one if() condition rather than few case conditions. Is there any special advantage use of switch-case combination than if() condition.
I appreciate your help all the time...
Eranga
|
|
|
|
|
Eranga Thennakoon wrote: Is there any special advantage use of switch-case combination than if() condition.
I prefer switch for the below manner.
enum STATUS { St_A, St_B, St_C };
MyClass::STATUS MyClass::GetStatus();
switch(GetStatus())
{
case MyClass::St_A:
case MyClass::St_B:
default:
}
Maxwell Chen
|
|
|
|
|
Eranga Thennakoon wrote: if(strString.at(i) == ' ')
{
iSpace ++;
}
if(strString.at(i) == '\t')
{
iTabs ++;
}
if(strString.at(i) == '\r')
{
iRet ++;
}
This is a moot point since a better solution has already been provided but I wanted to mention it anyhow. It does not make any sense to test a character three times when it can have only one value. In other words, if you find it to be a space, why check to see if it is also a tab or return? Use else with the latter two conditions.
"Normal is getting dressed in clothes that you buy for work and driving through traffic in a car that you are still paying for, in order to get to the job you need to pay for the clothes and the car and the house you leave vacant all day so you can afford to live in it." - Ellen Goodman
"To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne
|
|
|
|
|
Another solution might be:
int nCount = std::count(strString.begin(), strString.end(), ' ');
nCount += std::count(strString.begin(), strString.end(), '\r');
nCount += std::count(strString.begin(), strString.end(), '\t');
"Normal is getting dressed in clothes that you buy for work and driving through traffic in a car that you are still paying for, in order to get to the job you need to pay for the clothes and the car and the house you leave vacant all day so you can afford to live in it." - Ellen Goodman
"To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne
|
|
|
|
|
But that definitely is the slowest alternative, as every count-algorithm is just the contemporary way of writing a loop.
OTOH std::count , together with the char classification mentioned above - thats style!
Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all. Douglas Adams, "Dirk Gently's Holistic Detective Agency"
|
|
|
|
|
jhwurmbach wrote: But that definitely is the slowest alternative...
Nowhere did I imply that it was optimal. I was just giving the OP another option, that's all. If the string is only going to be processed once or twice, less efficient but easier-to-read code is sometimes the way to go.
"Normal is getting dressed in clothes that you buy for work and driving through traffic in a car that you are still paying for, in order to get to the job you need to pay for the clothes and the car and the house you leave vacant all day so you can afford to live in it." - Ellen Goodman
"To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne
|
|
|
|
|
I know that you know.
But the casual reader might take this idiom as "Recommended by David Crow"!
Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all. Douglas Adams, "Dirk Gently's Holistic Detective Agency"
|
|
|
|
|
Hi, I had a problem in reading a particular string of a text file in C++.
For example, I had a text file that looks like the one below:
Variable = .iso.org.dod.internet.private.enterprises.9.9.273.1.3.1.1.3.1.8.105.118.116.108.95.97.112.49.0.2.45.4.155.81<br />
Value = Integer32 -44<br />
<br />
End of MIB subtree.<br />
<br />
I only wanted to read the integer "-44" from the text file in the C++ prog, but I donno how to read it without reading the "Variable = .iso.org.dod.internet.private.enterprises.9.9.273.1.3.1.1.3.1.8.105.118.116.108.95.97.112.49.0.2.45.4.155.81
Value = Integer32 " strings.
My partially written code to read the file is given as below:
apfile=fopen("ap1.txt","r+");<br />
<br />
if (apfile==NULL)<br />
{<br />
cout<<"Error opening file ap1.txt"<<endl;<br />
fclose (apfile);<br />
return -1;<br />
}<br />
<br />
else<br />
{<br />
while (!feof(apfile)) <br />
{<br />
<br />
}<br />
}
Anyone can help me to get only the integer value of "-44" from the ap1.txt in the C++ programming? Thanks!
|
|
|
|
|
You have to read everything before the thing you seek. You just have to skip it.
This means that you have to parse the file -- which means to to read the contents and interpret it...
Without knowing the format of the file, I can't help you. But you should start by understanding the format of the file you are reading....
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br />
Peter Weyzen<br />
Staff Engineer<br />
<a href="http://www.soonr.com">SoonR Inc -- PC Power delivered to your phone</a>
|
|
|
|
|
first of all, thanks for ur reply. I tried another method to open and read the whole txt file using the getline method as below.
#include <fstream><br />
#include <string><br />
#include<iostream><br />
using namespace std;<br />
<br />
int main()<br />
{<br />
string str;<br />
<br />
ifstream myFile("ap1.txt");<br />
if(! myFile)<br />
{<br />
cout<<"Error!"<<endl;<br />
return -1;<br />
}<br />
while(! myFile.eof())<br />
{<br />
<br />
getline(myFile, str);<br />
str; <br />
cout<<str<<endl;<br />
<br />
}<br />
myFile.close();<br />
return 0;<br />
}
Sorry that I don't really quite understand what do you mean by the format of the file? I thought the format of the file is a text file? Sorry for my blurness
|
|
|
|
|
Not that simple. The format includes how the text is laid out.
Is each line the same length? Will it always be Variable= then Value=?
Will you have gaps in between sometimes? Chapter headings?
Lot's of things you can trip up on!
Iain.
|
|
|
|
|
As for whether it's the same length or not, I'm not sure as I'm using snmputil to read the mibs of the signal strength of a particular AP. The length may change if on different AP? But the format of the output will always be "Varible=" on the first line and the second line is "Value= " when all written to a .txt file.
|
|
|
|
|
If the lengths are not guaranteed, then you're just going to have to read in all the information, and just only bother to keep the bits you care about.
Iain.
|
|
|
|
|
So I have to search for the string "value=" and frm there to extract the -44 value? Is tht wad u mean by keeping the bits?
My prog now is currently reading all the info but I donno how to screen away the first line, and read the -44 frm the second line.
Thanks alot for ur valuable reply though. Appreciate tht.
|
|
|
|
|
Sort of...
What I mean is that you read in every line.
Read a Line;
Does it start with Value = ?
Yes...
Does it have Integer32 next?
Yes...
Grab the -44 part, and keep it somehow. A list, email it to your best friend, whatever you want.
No...
Move on to the next line!
By "keeping the bits", I mean "do whatever you like with the information". You must be interested in it for some reason. That will influence what you do with the information.
I did notice on rereading your question that there is a phrase "Integer32". Are they all the same type?
Iain.
|
|
|
|
|
sorry for the very very late reply...
ya, there's always a Integer32 whenever I run the prog and saved it to a text file. Tht's the format of the output.
What if I had 2 lines tht have Integer32 but different values? how am I supposed to extract the values? Fo e.g. like the one below:
Variable = .iso.org.dod.internet.private.enterprises.9.9.273.1.3.1.1.3.1.8.105.118.116.108.95.97.112.49.0.2.45.4.155.81<br />
Value = Integer32 -39<br />
<br />
Variable = .iso.org.dod.internet.private.enterprises.9.9.273.1.3.1.1.3.1.8.105.118.116.108.95.97.112.49.0.32.166.80.182.220<br />
Value = Integer32 -39<br />
<br />
End of MIB subtree.<br />
<br />
|
|
|
|
|
In the example you give, the Value is the same for each.
You're doing the same thing... Just loop through the file, reading one string at a time.
If it's blank, move on.
Then take turns making sure the line starts with variable , or value , then interpret the rest of the line as you want.
I'm guessing you're meant to store the Variable name, matched against the Value value in some sort of map, or even a database, then look up pairs later on in your program.
Or,
If you just want a list of values, read each line, and if it doesn't start with Value, then move on to the next line.
How you handle the imput as it comes really depends on the job you're doing - and that question can be solved by reading your spec sheet, talking to yout customer or manager?
From the Variable names, this doesn't look like a hobby project. I'm sure there's someone who can tell you what they want done / kept from this input. From there, just write the code (with test cases, etc).
At the moment, it sounds like you're not sure what you're meant to do with this data - and that's something we can't help with.
Good luck,
Iain/
|
|
|
|
|
I appreciate ur help, I hope I could solve the prob soon...
|
|
|
|