Regular expression executing before the other one - compilation

i am having a problem with my code
alphabet [a-zA-Z]
var {alphabet}+[{chiffre}{alphabet}_]*
{varIntDecl} {
for(int i=5 ;i<yyleng;i++)tab[cmp].token[i-5]=yytext[i]; strcpy(tab[cmp].value,"0");strcpy(tab[cmp].type,"Var");
tab[cmp].indiceTS= cmp;
strcpy(tab[cmp++].typeValeur,"int");
yylval.indiceTS=cmp;
return (INTVARIABLEDECL);
}
{var} {
for(int i=0;i<cmp;i++){
if(!strcmp(tab[i].token,yytext)) {
return (VARINT);
}
}
printf("Error Variable non trouvé Please Declare First ");
}
varIntDecl {int}{blancs}{var};
when i'm executing this
i have a yacc part but it's irrelevant to this
i'm getting this conflict of var executing everytime even tho it's not what i wanted to do
here is the result of execution:
int abc
Error Variable non trouvé Please Declare First
int adc
Error Variable non trouvé Please Declare First

Related

why the printf statement is executed once inside the for loop while its indentation match the for loop indentation?

Consider the following code:
int main()
{
char a[100]="axc axb cxa";
int i,j=0;
while (a[j]!='\0')
j++;
for(i=j;i>=0;i--)
if(a[i]=='\0' || a[j]==' ')
printf("%d\n%c",i,a[i-1]-32);
return 0;
}
In the above code, my understanding says the printf will be executed after completing the for loop and the value of i will be '-1'. According to output, the value of i is 11. But why? Can anyone please explain?

Passing a temporary stream object to a lambda function as part of an extraction expression

I have a function which needs to parse some arguments and several if clauses inside it need to perform similar actions. In order to reduce typing and help keep the code readable, I thought I'd use a lambda to encapsulate the recurring actions, but I'm having trouble finding sufficient info to determine whether I'm mistakenly invoking undefined behavior or what I need to do to actualize my approach.
Below is a simplified code snippet of what I have currently:
int foo(int argc, char* argv[])
{
Using ss = std::istringstream;
auto sf = [&](ss&& stream) -> ss& {
stream.exceptions(ss::failbit);
return stream;
};
int retVal = 0;
bool valA = false;
bool valB = false;
try
{
for(int i=1; i < argc; i++)
{
std::string arg( argv[i] );
if( !valA )
{
valA = true;
sf( ss(arg) ) >> myInt;
}
else
if( !valB )
{
valB = true;
sf( ss(arg) ) >> std::hex >> myOtherInt;
}
}
}
catch( std::exception& err )
{
retVal = -1;
std::cerr << err.what() << std::endl;
}
return retVal;
}
First, based on what I've read, I don't think that specifying the lambda argument as an rvalue reference (ss&&) is doing quite what I want it to do, however, trying to compile with it declared as a normal reference (ss&) failed with the error cannot bind non-const lvalue reference of type 'ss&'. Changing ss& to ss&& got rid of the error and did not produce any warnings, but I'm not convinced that I'm using that construct correctly.
I've tried reading up on the various definitions for each, but the wording is a bit confusing.
I guess ultimately my questions are:
Can I expect the lifetime of my temporary ss(arg) object to extend through the entire extraction expression?
What is the correct way to define a lambda such that I can use the lambda in the way I demonstrate above, assuming that such a thing is actually possible?

Don't indent Xcode-style commented-out code

Is there currently a way (other than explicitly suppressing formatting for a code segment) to get clang-format to not indent Xcode-style commented out code? That's // at the beginning of the line:
int f()
{
// return 1;
return 2;
}
Xcode does this comment-out style on Cmd+/.
clang-format, when run, indents the comment:
int f()
{
// return 1;
return 2;
}
which Xcode still successfully uncomments-out using the same shortcut, but resulting in inconsistent indentation:
int f()
{
return 1;
return 2;
}
I tried (ab)using CommentPragmas for this purpose, unsuccessfully. I thought maybe I'm doing the spaces in the regex wrong, but even with CommentPragmas: '^aaaa':
int f()
{
//aaaareturn 1;
return 2;
}
gets indented to
int f()
{
//aaaareturn 1;
return 2;
}
So either I'm still doing something wrong, or CommentPragmas will still indent comments, even if not otherwise re-flowing them.

Distance edit array output

I am doing an edit distance with the user input. I am storing my values in array. then the edit distance will compare the user input with my array of strings. I am doing a loop that if the edit distance is more than 2 it will display invalid else valid.
The only problem I've got is that although the program is working out fine, the output is the result of all the '28' strings that I have in my array. I would like to display only invalid or valid once.
Test is my array of strings and user is - String user - the user input.
void testingLD()
{
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
println ("Invalid re-input");
}
else
{
println ("Valid");
}
}
}
You have your print line functions inside your loop so they get printed once per iteration.
Try this.
void testingLD()
{
boolean isValid = true; // assume true, check each and update
// begin loop
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
isValid = false;
break; // don't need to test the rest of the loop if we already found a false
}
}
// end loop
if(isValid){
println("Valid");
}else{
println("Invalid re-input");
}
}
Similarly you could count the number of valid int validCount = 0; validCount++ and then display stats about how many were valid, the percentage etc. Or keep an array of the invalid strings and display those as the ones that fail etc!
Wrap up:
When you want to check an entire collection or array for some condition and output one answer make sure to have your output outside of the loop!

C++ Ensuring that user input value is int only [duplicate]

This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 8 years ago.
I am a little new to C++ and would really appreciate any input or suggestions! So with our intro course projects I have been looking for a way to ensure that when the prog. is asking for int values it correctly responds! That is it states its invalid in cases of both a double as well as string being entered! So if cin >> intVariable ... intVariable will not accept cin entry of "abdf" or 20.01.
So to achieve this I wrote the following function...It works but I am looking for your thoughts on how this process can be further improved!
void getIntegerOnly(int& intVariable, string coutStatement)
{
bool isInteger; // Check if value entered by user is int form or not
string tmpValue; // Variable to store temp value enetered by user
cout << coutStatement; // Output the msg for the cin statement
do
{
cin >> tmpValue; // Ask user to input their value
try // Use try to catch any exception caused by what user enetered
{
/* Ex. if user enters 20.01 then the if statement converts the
string to a form of int anf float to compare. that is int value
will be 20 and float will be 20.01. And if values do not match
then user input is not integer else it is. Keep looping untill
user enters a proper int value. Exception is 20 = 20.00 */
if (stoi(tmpValue) != stof(tmpValue))
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
else
{
isInteger = true; //Set to true!
clear_cin(); // Clear cin to ignore all text and space in cin!
}
}
catch (...) // If the exception is trigured!
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
} while (!isInteger); //Request user to input untill int clause met
//Store the int value to the variable passed by reference
intVariable = stoi(tmpValue);
}
This is simply an example of getting users age and age is greater than zero when running a Win32 console based application! Thank you for the feedback :)
One way would be something like the following:
std::string str;
std::cin >> str;
bool are_digits = std::all_of(
str.begin(), str.end(),
[](char c) { return isdigit(static_cast<unsigned char>(c)); }
);
return are_digits ? std::stoi(str) : throw std::invalid_argument{"Invalid input"};
and catch the exceptions on the calling side (stoi can also throw std::out_of_range).
You can leverage the second parameter of stoi().
string tmpValue;
size_t readChars;
stoi(tmpValue, &readChars);
if(readChars == tmpValue.length())
{
// input was integer
}
EDIT: this will not work for strings containing "." (for example integers passed in scientific notation).
This is not my work, but the answer to this question is what you want. Pass the string to it as a reference. It will return true is your string is an integer.
How do I check if a C++ string is an int?

Resources