"usage:\n\tll '(a+a)'" meaning in ll1 parser program - cpu-usage

I am unable to understand what is the role of "usage:\n\tll '(a+a)'" in the code. What is its function?? I am using g++ compiler to compile the code. If more than 2 arguments are passed in command prompt then problem occurs.
#include <iostream>
#include <map>
#include <stack>
enum Symbols {
TS_L_PARENS,
TS_R_PARENS,
TS_A,
TS_PLUS,
TS_EOS,
TS_INVALID,
NTS_S,
NTS_F
};
enum Symbols lexer(char c)
{
switch(c)
{
case '(': return TS_L_PARENS;
case ')': return TS_R_PARENS;
case 'a': return TS_A;
case '+': return TS_PLUS;
case '\0': return TS_EOS;
default: return TS_INVALID;
}
}
int main(int argc, char **argv)
{
using namespace std;
if (argc < 2)
{
cout << **"usage:\n\tll '(a+a)'"** << endl;
return 0;
}
map< enum Symbols, map<enum Symbols, int> > table;
stack<enum Symbols> ss; // symbol stack
char *p; // input buffer
ss.push(TS_EOS); // terminal, $
ss.push(NTS_S); // non-terminal, S
p = &argv[1][0];
table[NTS_S][TS_L_PARENS] = 2;
table[NTS_S][TS_A] = 1;
table[NTS_F][TS_A] = 3;
while(ss.size() > 0)
{
if(lexer(*p) == ss.top())
{
cout << "Matched symbols: " << lexer(*p) << endl;
p++;
ss.pop();
}
else
{
cout << "Rule " << table[ss.top()][lexer(*p)] << endl;
switch(table[ss.top()][lexer(*p)])
{
case 1: // 1. S → F
ss.pop();
ss.push(NTS_F); // F
break;
case 2: // 2. S → ( S + F )
ss.pop();
ss.push(TS_R_PARENS); // )
ss.push(NTS_F); // F
ss.push(TS_PLUS); // +
ss.push(NTS_S); // S
ss.push(TS_L_PARENS); // (
break;
case 3: // 3. F → a
ss.pop();
ss.push(TS_A); // a
break;
default:
cout << "parsing table defaulted" << endl;
return 0;
break;
}
}
}
cout << "finished parsing" << endl;
return 0;
}

cout is the function, "usage:\n\tll '(a+a)'" is a string literal passed to the function. This bit in your question prints:
usage:
ll '(a+a)'

Related

How to change this pass by reference into pointer as function parameter

wanting to ask how to change this pass by reference into pass by pointer, cause some of my school works need pass by pointer and i doesn't really understand how to modified this code using pass by pointer
void convert(string &s){
for (int i =0; i<s.length(); i++){
s[i] = toupper(s[i]);
}
}
int main(){
string name;
cout<<"Enter your name"<<endl;
getline(cin,name);
convert(name);
cout<<name<<endl;
return 0;
}
First of all, there are some minor errors in the code.
Inlcude necessary headers.
Use std:: namespace prefix.
#include <iostream>
#include <string>
#include <cctype>
void convert(std::string &s){
for (int i =0; i < s.length(); i++){
s[i] = std::toupper(s[i]);
}
}
int main(){
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
convert(name);
std::cout << name << std::endl;
return 0;
}
Using pointer version?
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#define SIZE 100
void convert(char *s, size_t size){
for (int i =0; i < size; i++){
s[i] = std::toupper(s[i]);
}
}
int main(){
char name[SIZE];
std::cout << "Enter your name: ";
std::fgets(name, SIZE, stdin);
convert(name, strlen(name));
std::cout << name << std::endl;
return 0;
}
Another version using pointers
#include <iostream>
#include <string>
#include <cctype>
void convert(std::string *s){
for (int i =0; i < s -> length(); i++){
(*s)[i] = std::toupper((*s)[i]);
}
}
int main(){
std::string *name = new std::string();
std::cout << "Enter your name: ";
std::getline(std::cin, *name);
convert(name);
std::cout << *name << std::endl;
delete name;
return 0;
}

What does this recursion function output?

I'm just starting to learn recursion and I don't understand the output, which is 39493. Could you explain?
struct Node {
int value;
Node* next;
}
head --> 3 --> 9 --> 4 --> NULL
void f4(Node* n) {
if(n == NULL)
return;
if(n->next == NULL)
cout << n->value << “ ”;
else {
cout << n->value << “ ”;
f4(n->next);
cout << n->value << “ ”;
}
}
Your f4 function prints out a linked list of integers, forwards (from the head/root to the tail) and then backwards. It does this because the inner call of f4 within the else clause is surrounded by two cout statements, which will both print the current node's value, adding a stack frame (new execution context with the next node) in between. The last node (the tail) is captured by if(n->next == NULL), and there's only one cout statement in this clause, so the tail only prints once.
I added a main method to illustrate this:
#include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
};
void f4(Node* n) {
// This will never be reached
// except if f4 is called with NULL directly
if(n == NULL)
return;
if(n->next == NULL)
cout << n->value << endl;
else {
cout << n->value << endl;
f4(n->next);
cout << n->value << endl;
}
}
int main() {
cout << "Starting!" << endl;
Node n1 = {1, 0};
Node n2 = {2, &n1};
Node n3 = {3, &n2};
// get pointer to n3 -> n2 -> n1
f4(&n3);
return 0;
}
Output:
Starting!
3
2
1
2
3
To understand the stack frame (recursive call) handling mechanism:
https://www.bottomupcs.com/elements_of_a_process.xhtml.
You might understand it better by adding additional markers to differentiate the cout << n->value << endl on different lines.

Expected unqualified-id before '.' token

I'm pretty new at c++ so talk caveman to me. I'm trying to get the code to run in a loop and and when the loop is done calculate the total and everything ordered. I'm running into this error and I'm not sure why.
[Error] expected unqualified-id before '.' token
#include <iostream>
#include<string>
#include <vector>
using namespace std;
string again;
char pType, pSize, topping, temp;
const int SMALL = 1;
int type = 0, size = 0;
const int MEDIUM = 2;
const int LARGE = 3;
const int DEEPDISH = 1;
const int HANDTOSSED = 2;
const int PAN = 3;
double total = 0;
class Pizza
{
private:
int type;
int size;
bool cheese;
bool pepperoni;
public:
Pizza();
int getType();
int getSize();
bool getCheese();
bool getPepperoni();
void setType(int t);
void setSize(int s);
void setCheese(bool choice);
void setPepperoni(bool choice);
void outputDescription();
double computePrice();
};
class Order
{
private:
vector<Pizza> c;
public:
Order();
void customerOrder();
void customerTotal();
void customerinput();
};
Pizza::Pizza()
{
type = DEEPDISH;
size = SMALL;
cheese = pepperoni = false;
}
int Pizza::getType()
{
return type;
}
int Pizza::getSize()
{
return size;
}
bool Pizza::getCheese()
{
return cheese;
}
bool Pizza::getPepperoni()
{
return pepperoni;
}
void Pizza::setType(int t)
{
type = t;
}
void Pizza::setSize(int s)
{
size = s;
}
void Pizza::setCheese(bool choice)
{
cheese = choice;
}
void Pizza::setPepperoni(bool choice)
{
pepperoni= choice;
}
void Pizza::outputDescription()
{
switch (size)
{
case SMALL:
cout << "Small "; break;
case MEDIUM:
cout << "Medium "; break;
case LARGE:
cout << "Large "; break;
default:
cout << "Unknown" ;
}
switch (type)
{
case DEEPDISH:
cout << "deepdish "; break;
case HANDTOSSED:
cout << "hand tossed "; break;
case PAN:
cout << "pan "; break;
default:
cout << "Unknown";
}
cout << "pizza";
}
double Pizza::computePrice()
{
double cost = 0.0;
switch (size)
{
case SMALL:
cost += 10; break;
case MEDIUM:
cost += 14; break;
case LARGE:
cost += 17; break;
}
if (cheese)
cost += 2.0;
if (pepperoni)
cost += 2.0;
return cost;
}
Order custmizedTotal;
Pizza myPizza;
bool done=false;
void Order::customerinput(){
while ( again == "y"){
cout << "What sized pizza, please enter S, M OR L: ";
cin >> pSize;
cin.clear();
switch(pSize)
{
case 'S': case 's':
size = SMALL; break;
case 'M': case 'm':
size = MEDIUM; break;
case 'L': case 'l':
size = LARGE; break;
}
cout << "What type of pizza, enter D for Deepdish, H for Hand tossed, and P for Pan: ";
cin >> pType;
cin.clear();
switch(pType)
{
case 'D': case 'd':
type = DEEPDISH; break;
case 'H': case 'h':
type = HANDTOSSED; break;
case 'P': case 'p':
type = PAN; break;
}
myPizza.setSize(size);
myPizza.setType(type);
cout << "Would you like cheese (y/n)? ";
cin >> topping;
cin.clear();
if (topping == 'Y' || topping == 'y')
myPizza.setCheese(true);
cout << "Would you like pepperoni (y/n)? ";
cin >> topping;
cin.clear();
if (topping == 'Y' || topping == 'y')
myPizza.setPepperoni(true);
cout << endl
<< "Your order: ";
myPizza.outputDescription();
cout << endl;
cout << "Price: $" << myPizza.computePrice() << endl;
cout << "Again? (y/n)";
cin >> again;
}
}
void Order::customerTotal(){
cout << "Your Total order is: " << endl;
for(int i=0; i<c.size(); i++)
{
c[i].outputDescription();
cout << endl;
cout << c[i].computePrice();
cout << endl;
total=total+c[i].computePrice();
}
cout << "Totat Cost: $" << total;
cout << endl;
c.push_back(myPizza);
}
int main()
{
custmizedTotal.customerinput();
//Order.customerinput();
if(again != "y"){
custmizedTotal.customerTotal();
}
return 0;
}
Replace
int main(){
Order.customerinput(); //error is here
if(again != "y"){
custmizedTotal.customerTotal();
}
return 0;
}
By:
int main(){
custmizedTotal.customerinput(); // Change this line
if(again != "y"){
custmizedTotal.customerTotal();
}
return 0;
}
The second error that you have as caused because you forgot to define Order constructor.
Add this to your code (above main() method):
Order::Order(){
// Set the initial values for order
}
You also forgot to add customerOrder method (but this does not cause error since you are not using this method):
void Order::customerOrder() {
}

What is the defined behavior of SQLite when interleaving statements that affect each other?

In SQLite if I prepare a SELECT statement and begin stepping through it, then before the last row of the results is reached I execute another statement that has an effect on the SELECT statement that I am stepping through, what is the expected result?
I can't find anything in the SQLite documentation about what is supposed to happen but it seems like an extremely common case when programming in a multi-threaded environment.
Below is a c++ file that can be compiled and run on Windows to demonstrate the situation.
#include "stdafx.h"
#include "sqlite3.h"
#include <Windows.h>
#include <iostream>
#include <Knownfolders.h>
#include <Shlobj.h>
#include <wchar.h>
#include <comdef.h>
using namespace std;
int exec_sql(sqlite3 *db, const char* sql)
{
char *errmsg;
int result = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
if (result != SQLITE_OK) {
cout << errmsg << endl;
return -1;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Running jsqltst with SQLite version: ";
cout << sqlite3_libversion();
cout << endl;
PWSTR userhome;
if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Profile, NULL, NULL, &userhome))) {
cout << "Failed getting user home dir\n";
return -1;
}
wcout << "User home: " << userhome << endl;
wchar_t *ws1 = userhome, *ws2 = L"\\test.sqlite";
wstring dbpath_str(ws1);
dbpath_str += wstring(ws2);
_bstr_t dbpath(dbpath_str.c_str());
cout << "DB path: " << dbpath << endl;
sqlite3 *db;
int result = sqlite3_open_v2(dbpath, &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
if (result != SQLITE_OK) {
cout << sqlite3_errmsg(db) << endl;
return -1;
}
const char * create_stmt = "CREATE TABLE IF NOT EXISTS atable (id INTEGER PRIMARY KEY, name TEXT, number INTEGER);";
if (exec_sql(db, create_stmt) != 0) {
return -1;
}
const char * delete_stmt = "DELETE FROM atable;";
if (exec_sql(db, delete_stmt) != 0) {
return -1;
}
const char * insert_stmt = "INSERT INTO atable (name,number) VALUES ('Beta',77),('Alpha',99);";
if (exec_sql(db, insert_stmt) != 0) {
return -1;
}
sqlite3_stmt* select_ss;
const char * select_stmt = "SELECT * FROM atable;";
result = sqlite3_prepare_v2(db, select_stmt, -1, &select_ss, NULL);
if (result != SQLITE_OK) {
cout << sqlite3_errmsg(db) << endl;
return -1;
}
int i = 0;
boolean gotrow;
do {
result = sqlite3_step(select_ss);
gotrow = result == SQLITE_ROW;
if (gotrow) {
i++;
cout << "I got a row!" << endl;
if (i == 1) {
if (exec_sql(db, insert_stmt) != 0) {
return -1;
}
}
}
} while (gotrow);
cout << "Last result: " << result << ", errstr: " << sqlite3_errstr(result) << endl;
result = sqlite3_finalize(select_ss);
if (result != SQLITE_OK) {
cout << sqlite3_errmsg(db) << endl;
return -1;
}
return 0;
}
SQLite's behaviour for concurrent statements in the same transaction is neither documented nor defined.
As you have seen, newly inserted records might be seen when a SELECT's cursor has not yet reached that part of the table.
However, if SQLite needed to create a temporary result table for sorting or grouping, later changes in the table will not appear in that result.
Whether you have a temporary table or not might depend on decisions made by the query optimizer, so this is often not predictable.
If multiple threads access the same connection, SQLite will lock the DB around each sqlite3_step call.
This prevent data corruption, but you will still have the problem that automatic transaction end when their last active statement ends, and that explicit transaction will fail the COMMIT if there is some other active statement.
Multi-threaded programs are better off using (at least) one connection per thread.

Qt Q_ENUM property from QVariant(qulonglong).

Consider the following Qt code:
class Foo : public QObject {
Q_OBJECT
Q_ENUMS(E)
Q_PROPERTY(E x READ x WRITE set_x)
public:
enum E {
a = 0,
b = 1,
c = 2
};
E x() const { return x_; }
void set_x(E value) { x_ = value; }
private:
E x_;
};
int main (int argc, char **argv) {
QCoreApplication app(argc, argv);
Foo f;
f.setProperty("x", Foo::c);
std::cout << f.property("x").toInt() << std::endl; // 2
f.setProperty("x", QVariant((int)1));
std::cout << f.property("x").toInt() << std::endl; // 1
f.setProperty("x", QVariant((long long)0));
std::cout << f.property("x").toInt() << std::endl; // should be 0. is 1.
}
Why does it work that way?
If you test the return value of setProperty, you will see that the set is failing:
ok = f.setProperty("x", QVariant((long long)0));
std::cout << ok << std::endl; // 0, i.e. false
The relevant part of the Qt code is in qmetaobject.cpp, annotated below:
if (isEnumType()) {
if (v.type() == QVariant::String) {
// ... we won't get here.
} else if (v.type() != QVariant::Int && v.type() != QVariant::UInt) {
// We got here because we didn't provide an int or uint.
// This will be 0...
int enumMetaTypeId = QMetaType::type(qualifiedName(menum));
// ... which means this will return false; the property will not be set.
if ((enumMetaTypeId == 0) ||
(v.userType() != enumMetaTypeId) ||
!v.constData())
return false;
// ... we never get here
}
}
// ... we never get here
So the behavior seems to be by design: enum properties can only be set using QVariant objects with a type of int or uint.

Resources