Turbo C++ ignoring if and else if statements and jumping to else when using a char [duplicate] - turbo-c++

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 7 years ago.
I'm a student(newbie) and everything I've learned, I just applied here but string isn't clearly explained by our instructor. So I'm having problem with this code it doesn't accept the if else if and jumps on else. I'm using Turbo C++. I'm wondering what is wrong with here, since I'm totally newbie with these. Thank you in advance
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
clrscr();
char user[50],pass[50];
cout<< "Username: ";
gets(user);
cout<< "Password: ";
gets(pass);
if (user=="user" && pass=="pass"){
cout<< "ACCESS GRANTED";
}else if (user=="user"){
cout<< "Wrong Password";
}else if (pass=="pass"){
cout<< "Wrong Username";
}else
cout<< "Wrong Username and Password";
getch();
}

I can't find it, but this is clearly a duplicate and has nothing to do with the turbo C++ compiler. In C, you cannot compare strings that way. You need to do if (strcmp(user,"user") == 0) (strcmp returns 0 if the two strings are equal, otherwise it returns a positive or negative to indicate which is alphabetically "first")

In short: you cannot compare char[] using operator ==.
You should replace == with strcmp

Related

QRegularExpression: how to get the failing position?

I guess that this has had to be asked before, but cannot find anything about it.
I also think that maybe the answer is just right there but I can't see it either.
So, if QRegularExpression::match() has not a match, how do I know the position of the character that made the validation fail?
I'm pretty sure that internally, there should be some variable storing the "current position" as the string is being evaluated.
Yes, maybe there is backtracking in that evaluation so if the exact failing char is hard to get, at least the last good one could be easier.
Any hints? Thank you.
Edit (2022-08-08):
I'm starting to feel like it's possible that no one asked this before, in fact, considering how people think I am asking something like "why my regex does not work". Not my case.
This is not about a particular regular expression. It's about Qt's class QRegularExpression.
I apologize if I've not been clear. I've tried to explain the best I could since the very beginning.
Anyway, let's say you have one string, to be evaluated against some (ANY) regex. No match is found. Then I want to know, if possible, the point where the evaluation failed.
This regex: "abc"
This string: "abd", failing position: 2
This regex: "abc"
This string: "acb", failing position: 1
This regex: "abc"
This string: "xyz", failing position: 0
I feel very stupid asking this, mostly because I think it's a very basic question.
But it's not what you immediately think at first glance. I swear I searched for answers the most I could, but everything I got was about errors in the regexes themselves.
I hate this, but it works.
int getFailingPosition(QString sRegEx,QString sText) {
int iResult;
QRegularExpression rxRegEx;
QRegularExpressionMatch rxmMatch;
rxRegEx.setPattern(QRegularExpression::anchoredPattern(sRegEx));
for(iResult=sText.length();iResult>0;iResult--) {
rxmMatch=rxRegEx.match(sText);
if(rxmMatch.hasMatch())
break;
else {
rxmMatch=rxRegEx.match(
sText,
0,
QRegularExpression::MatchType::PartialPreferCompleteMatch
);
if(rxmMatch.hasPartialMatch())
break;
}
sText.chop(1);
}
return iResult;
}
Tests:
#define REGEX_USA_ZIPCODE "\\d{4}?\\d$|^\\d{4}?\\d-\\d{4}"
#define REGEX_SIGNED_NUMBER "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"
#define REGEX_ISO8601_DATE "\\d{4}-(0[1-9]|1[012])-(0[1-9]|[12]\\d|3[0-1])"
#define REGEX_USA_PHONE "\\(?\\d{1,3}?\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}"
qDebug() << getFailingPosition("abc","abcd"); // 3
qDebug() << getFailingPosition("abc","abd"); // 2
qDebug() << getFailingPosition("abc","acb"); // 1
qDebug() << getFailingPosition("abc","xyz"); // 0
qDebug() << getFailingPosition("abc","x"); // 0
qDebug() << getFailingPosition("abc",""); // 0
qDebug() << getFailingPosition("abc","a"); // 1
qDebug() << getFailingPosition("abc","ab"); // 2
qDebug() << getFailingPosition(REGEX_USA_ZIPCODE,"12345-1"); // 7 (missing chars)
qDebug() << getFailingPosition(REGEX_SIGNED_NUMBER,"-0.123e"); // 7 (missing chars)
qDebug() << getFailingPosition(REGEX_ISO8601_DATE,"2021-23-31"); // 5 (unexpected char)
qDebug() << getFailingPosition(REGEX_USA_PHONE,"202-3(24)-3000"); // 5 (unexpected char)
getFailingPosition() should be called only after we're sure there is not a match, or it would return the string length, giving the wrong idea that something's missing.
This should have a built-in function...

Parsing a hex nr byte by byte

I'm trying to parse a hex number byte by byte, and concatenate to a string the representation of each byte, in the order they're stored in memory. (for a little test on endianness, but that's not important I guess).
Here is the code (please ignore the glaring unit-test issues with it :D; also, some of the code might look weird since initially the display_bytes method took in a char* not an int8_t*, but I thought using an int8_t might make it more obvious to me, what the issue is)
TEST_CLASS(My001littlebigendian)
{
public:
TEST_METHOD(TestMethod1)
{
int i = 0x12345678;
display_bytes((int8_t*)&i, sizeof(i));
}
void display_bytes(int8_t* b, int length)
{
std::stringstream ss;
for (int i = 0; i < length; ++i)
{
int8_t signedCharRepresentation = *(b + i); //signed char has 1 byte
int8_t signed8ByteInt = (int8_t)signedCharRepresentation; //this is not ok
int32_t signed32ByteInt = (int32_t)signedCharRepresentation; //this is ok. why?
//ss << std::hex << signed8ByteInt; //this is not ok. why?
ss << std::hex << signed32ByteInt; //this is ok
}
std::string stringRepresentation = ss.str();
if (stringRepresentation.compare("78563412") == 0)
{
Assert::IsTrue(true, L"machine is little-endian");
}
else if(stringRepresentation.compare("01234567") == 0)
{
Assert::IsTrue(true, L"machine is big-endian");
}
else
{
Assert::IsTrue(true, L"machine is other-endian");
}
}
};
Now, what I don't understand (as hopefull the comments make clear) is why does this only work when I cast each byte to a 4 byte int, and not an 1 byte int. Since I am working with chunks of 1 byte. Intuitively it would make me think doing it like this should cause some sort of overflow? But it seems not.
I've not dug deeper into why this is the issue yet, since I was hoping to not need to. And maybe if someone with more knowledge in this area can give me nudge in the right direction, or maybe even an outright answer if I'm missing something very obvious. (which I do feel I might be, since I'm not used to working at this low level).

Finding a specific character in a file in Qt

How can i find a specific character in a QFile which has a text in it?
for example i have ' $5000 ' written somewhere in my file. in want to find the "$" sign so i will realize that I've reached the number.
I tried using QString QTextStream::read(qint64 maxlen) by putting 1 as the maxlen :
QFile myfile("myfile.txt");
myfile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream myfile_stream(&myfile);
while(! myfile_stream.atEnd())
{
if( myfile_stream.read(1) == '$')
{
qDebug()<<"found";
break;
}
}
and i get "error: invalid conversion from 'char' to 'const char* "
i also tried using the operator[] but apparently it can't be used for files.
Read in a line at a time and search the text that you've read in
QTextStream stream(&myFile);
QString line;
do
{
line = stream.readLine();
if(line.contains("$"))
{
qDebug()<<"found";
break;
}
} while (!line.isNull());
The error message you've posted doesn't match the issue in your code. Possibly the error was caused by something else.
QTextStream::read returns QString. You can't compare QString and const char* directly, but operator[] can help:
QString s = stream.read(1);
if (s.count() == 1) {
if (s[0] == '$') {
//...
}
}
However reading a file by too small pieces will be very slow. If your file is small enough, you can read it all at once:
QString s = stream.readAll();
int index = s.indexOf('$');
If your file is large, it's better to read file by small chunks (1024 bytes for example) and calculate the index of found character using indexOf result and count of already read chunks.
a single char could be read with
QTextStream myfile_stream(&myfile);
QChar c;
while (!myfile_stream.atEnd())
myfile_stream >> c;
if (c == '$') {
...
}
myfile_stream.read(1) - this is not good practice, you should not read from file one byte at a time. Either read the entire file, or buffered/line by line if there is a risk for the file to be too big to fit in memory.
The error you get is because you compare a QString for equality with a character literal - needless to say that is not going to work as expected. A string is a string even if there is only one character in it. As advised - use either the [] operator or better off for reading - QString::at() const which is guaranteed to create no extra copy. You don't use it on the QFile, nor on the QTextStream, but on the QString that is returned from the read() method of the text stream targeted at the file.
Once you have the text in memory, you can either use the regular QString methods like indexOf() to search for the index of a contained character.
in want to find the "$" sign so i will realize that I've reached the
number.
It sounds to me that you're searching for the '$' symbol because you're more interested in the dollar value that follows it. In this case, I suggest reading the files line by line and running them through a QRegExp to extract any values you're looking for.
QRegExp dollarFind("\\$(\\d+)");
while(!myfile_stream.atEnd()){
QString line = myfile_stream.readLine();
if (dollarFind.exactMatch(line)){
QStringList dollars = dollarFind.capturedTexts();
qDebug() << "Dollar values found: " << dollars.join(", ");
}
}

Arduino passing char to function

I apologize if this is a stupid question (It probably is) but I am having a hard time getting a function to work correctly.
My code as it stands:
#define photoPin A0
char photoCode[] = "L";
void loop(void) {
analogSensor(photoPin, photoCode);
delay(5000);
}
void analogSensor(int sensorPin, char* sensorCode) {
//Poll the Photo Cell and append that to the buffer
int sensorValue=analogRead(sensorPin);
Serial.print(sensorCode);
sprintf(buf + strlen(buf), "," + sensorCode + ":%04i", sensorValue);
}
When I try to compile this, I get the following message:
In function 'void analogSensor(int, char*)':
i2c_Sensor:104: error: invalid operands of types 'const char [2]' and 'char*' to binary 'operator+'
But, if I comment out the sprintf line, it compiles fine, and ever 5 seconds, an "L" prints out on the screen. Ultimately, I am confused as all get out, and don't know where to turn at this point.
Any help is appreciated.
The last one the formatting got borked :)
I'm afriad you cant concatenate char* with the + operator :) You'd have to call sprintf or strcat :) See your local man pages.
Instead of this:
sprintf(buf + strlen(buf), "," + sensorCode + ":%04i", sensorValue);
Try this:
sprintf( buf+strlen(buf), ",%s:%04i", sensorCode, sensorValue );

get shift+numerical keys in qt using qkeyevent

I am using QKeyEvent to get the Shift+numeric key, but it return me the ascii for "!" instead of "1" so my problem is, is there any method or techniques to get the actual numeric value's ascii instead of ascii of "!" (special character). I also followed this thread:
Get key char (value) from keycode with shift modifier
but it does not seems to help me to get rid from this problem. Thanks in advance.
I believe at least as of version 4.8 there is no standard method to get the numeric ascii value. You could try a brute force method similar to the thread you linked.
if (e->modifiers() & Qt::ShiftModifier) {
switch(e->text()) {
case '!':
trans_key = '1';
break;
}
}

Resources