How to fix C++ error: expected unqualified-id - c++

I'm getting this error on line 6:
error: expected unqualified-id before '{' token
I can't tell what's wrong.
#include <iostream>
using namespace std;
class WordGame;
{ // <== error is here on line 6
public:
void setWord( string word )
{
theWord = word;
}
string getWord()
{
return theWord;
}
void displayWord()
{
cout << "Your word is " << getWord() << endl;
}
private:
string theWord;
}
int main()
{
string aWord;
WordGame theGame;
cin >> aWord;
theGame.setWord(aWord);
theGame.displaymessage();
}

There should be no semicolon here:
class WordGame;
...but there should be one at the end of your class definition:
...
private:
string theWord;
}; // <-- Semicolon should be at the end of your class definition

As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.
void setWord(const std::string& word) {
theWord = word;
}

Get rid of the semicolon after WordGame.
You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

Semicolon should be at the end of the class definition rather than after the name:
class WordGame
{
};

For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.
My situation was something like
mynamespace::MyObject otherObject
for (const auto& element: otherObject.myVector) {
// execute arbitrary code on element
//...
//...
}
From this code, my compiler kept telling me:
error: expected unqualified-id before for (const auto& element: otherObject.myVector) {
etc...
which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ; after declaring otherObject.

For anyone with this situation: I saw this error when I accidentally used my_first_scope::my_second_scope::true in place of simply true, like this:
bool my_var = my_first_scope::my_second_scope::true;
instead of:
bool my_var = true;
This is because I had a macro which caused MY_MACRO(true) to expand into my_first_scope::my_second_scope::true, by mistake, and I was actually calling bool my_var = MY_MACRO(true);.
Here's a quick demo of this type of scoping error:
Program (you can run it online here: https://onlinegdb.com/BkhFBoqUw):
#include <iostream>
#include <cstdio>
namespace my_first_scope
{
namespace my_second_scope
{
} // namespace my_second_scope
} // namespace my_first_scope
int main()
{
printf("Hello World\n");
bool my_var = my_first_scope::my_second_scope::true;
std::cout << my_var << std::endl;
return 0;
}
Output (build error):
main.cpp: In function ‘int main()’:
main.cpp:27:52: error: expected unqualified-id before ‘true’
bool my_var = my_first_scope::my_second_scope::true;
^~~~
Notice the error: error: expected unqualified-id before ‘true’, and where the arrow under the error is pointing. Apparently the "unqualified-id" in my case is the double colon (::) scope operator I have just before true.
When I add in the macro and use it (run this new code here: https://onlinegdb.com/H1eevs58D):
#define MY_MACRO(input) my_first_scope::my_second_scope::input
...
bool my_var = MY_MACRO(true);
I get this new error instead:
main.cpp: In function ‘int main()’:
main.cpp:29:28: error: expected unqualified-id before ‘true’
bool my_var = MY_MACRO(true);
^
main.cpp:16:58: note: in definition of macro ‘MY_MACRO’
#define MY_MACRO(input) my_first_scope::my_second_scope::input
^~~~~

I got this error because I was not declaring a variable and was using it further .
Here is my code why I was getting it.
It was because I was not declaring a variable for size of my >vector.
Just replace
int n=arr.size();
Replace Here,
int sumSubarrayMins(vector<int>& arr) {
int = arr.size();
long long sum;
long long ans =0;
for(long i =0;i<n;i++){
sum =0;
long mini=INT_MAX;
for(long long j =i;j<n;j++){
mini=min(mini,arr[j]);
sum+=mini;
}
ans+=sum;
}
return ans;
}

Related

How to iterate through a range-based for loop when the data type of the array is const char *?

I am trying to solve the following question:
https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/cpp in C++.
When I try to iterate over a range based for loop I get the following error ->
In file included from main.cpp:6:
./solution.cpp:14:13: error: invalid range expression of type 'const char *'; no viable 'begin' function available
for(auto x: in){
^ ~~
1 error generated.
The code ->
Also , further on I am also encountering an error while comparing, if(x!=' ') that I am comparing wrong data types, I am trying to understand the dereferencing concept and its escaping my understanding. can someone break down the explanation for me please?
#include <unordered_map>
#include <string.h>
using namespace std;
size_t duplicateCount(const std::string& in); // helper for tests
size_t duplicateCount(const char* in)
{
unordered_map<char , int> hash;
for(auto x: in){
cout<<"char:"<<x<<endl;
if(hash[x]>=0){
hash[x]+=1;
} else {
if(x!=" "){
hash[x]=0;
}
}
}
int ct=0;
for(auto x:hash){
if(x.second>1){
ct++;
}
}
return ct;
}
You just can't use range based for loops with plain old arrays. In your case you could use std::string_view as a wrapper around your char array:
const char* in = "hallo welt";
std::string_view sv(in);
for(const auto& x: sv){
std::cout<<"char:"<<x<<std::endl;
if(x == 'h')
std::cout<<"h-detected"<<std::endl;
}

How to pass std::cin to a class constructor?

I am trying to create a class which can read input from either a file stream or std::cin:
#include <string>
#include <iostream>
#include <mutex>
class A
{
public:
explicit A(std::istream& input)
: input_(input)
{
;
}
public:
void doSomething()
{
std::string word;
while (input_ >> word) {
std::cout << word << std::endl;
}
}
private:
std::istream& input_;
std::mutex mutex_;
};
int main()
{
auto a = A(std::cin);
a.doSomething();
return 0;
}
But the compiler gives the following output:
~/test/main.cpp: In function ‘int main()’:
~/test/main.cpp:31:22: error: use of deleted function ‘A::A(A&&)’
auto a = A(std::cin);
^
~/test/main.cpp:5:7: note: ‘A::A(A&&)’ is implicitly deleted because the default definition would be ill-formed:
class A
^
~/test/main.cpp:5:7: error: use of deleted function ‘std::mutex::mutex(const std::mutex&)’
In file included from /usr/include/c++/7/mutex:43:0,
from ~/test/main.cpp:3:
/usr/include/c++/7/bits/std_mutex.h:97:5: note: declared here
mutex(const mutex&) = delete;
^~~~~
How should I fix the error? Or generally, how do we create a class that can read input either from a file stream or std::cin?
Edit
Initially I tried to reduce the amount of code as much as possible, and in that process, I removed std::mutex part, which gave a very different compiler output. Plus, there was a typo where input_ was std::stream and #JerryJeremiah was correct in the first comment that it should be std::istream &.
Now, I think the question doesn't quite match the problem, as #acraig5075 also pointed out in the comment. And there are similar questions on Stack Overflow already, so I'm going to delete my question.
I found the answer.
std::mutex is not copyable, and the class containing it becomes not-copyable as well.
The code should be:
int main()
{
A a(std::cin);
a.doSomething();
return 0;
}

std::hash for __uint128_t

I am facing an issue hashing __uint128_t. Following is my code:
#include <iostream>
int main () {
__uint128_t var = 1;
std::cout << std::hash<__uint128_t> () (var) << "\n";
return 0;
}
I am getting the error as:
test.cpp: In function ‘int main()’:
test.cpp:5:40: error: use of deleted function ‘std::hash<__int128 unsigned>::hash()’
5 | size_t h = std::hash<__uint128_t> () (var);
| ^
How can I get the hash for __uint128_t? (Probably a very basic question but I have been stuck here for a while). Also, I would like to know the meaning of the error. Thanks in advance.
Taking a look at the docs on https://en.cppreference.com/w/cpp/utility/hash. You will have to write your own.
Here is some code for what a basic __uint128_t hash function might look like:
namespace std {
template<>
struct hash<__uint128_t> {
size_t operator()(__uint128_t var) const {
return std::hash<uint64_t>{}((uint64_t)var ^ (uint64_t)(var >> 64));
}
};
}
Note not tested or compiled.

c++ struct and "expected primary-expression" error

It's easier to explain with some code:
#include <iostream>
using namespace std;
struct test {
int one;
int two;
};
void insertdata(test & info)
{
cin >> info.one;
cin >> info.two;
}
int doitnow(test mytable[])
{
test info;
int i = 0;
for (i=0; i<3; i++) {
insertdata(test & info);
mytable[i] = info;
}
return i;
}
int main()
{
int total;
test mytable[10];
total = doitnow(test mytable[]);
cout << total;
}
So, I need to pass info by reference to the function insertdata, I need to use that function in doitnow to fill up a table and I need to show in the main function the number of items inserted in doitnow. I keep getting errors when I try to call functions:
teste.cpp: In function ‘int doitnow(test*)’:
teste.cpp:21:29: error: expected primary-expression before ‘&’ token
insertdata(test & info);
teste.cpp: In function ‘int main()’:
teste.cpp:33:30: error: expected primary-expression before ‘mytable’
total = doitnow(test mytable[]);
So, probably it's an obvious mistake but I'm a beginner at this.
Thanks for your help.
test& info is a definition. If you pass something to a function, you write an expression like info. It is automatically passed by reference because you specified info as a reference in the formal parameter list.
You also wrote
mytable[i] = info;
and not
mytable[i] = test & info;
didn't ya?
Use insertdata(info); instead.
Same goes for arrays. Use doitnow(test) instead.

Making a simple stack in C++

Hi I am making a simple stack class in C++ and am new to C++. I am having a few errors that I cannot figure out what they mean. Some help would be greatly appreciated! Here is my code:
Stack.h
#ifndef SStack
#define SStack
#include <cstdlib>
#include <string>
class SStack
{
public:
// Constructor
SStack( int cap);
// Copy Constructor
SStack( const SStack& s );
~SStack( );
void push ( const std::string& s);
std::string& pop ();
std::string& top () const;
bool IsEmpty () const;
int size() const;
int getCapacity() const;
// NONMEMBER FUNCTIONS for the bag class
// Precondition: s1.size( ) + s2.size( ) <= s1.Capacity.
// Postcondition: The stack returned is the union of s1 and s2.
SStack operator +(const SStack& s2);
private:
int Capacity; // Capacity is the maximum number of items that a stack can hold
std::string *DynamicStack;
int used; // How many items are stored in the stack
};
#endif
Stack.cpp
#include "SStack.h"
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
class SStack
{
public:
void SStack(int cap){
DyanmicStack = new string[cap];
Capacity = cap;
used = -1;
}
void SStack(const SStack& s){
DyanmicStack = new string[cap];
}
~SStack( ){
delete(DynamicStack);
}
void push(const string& s){
DynamicStack[used] = s;
used++;
}
string& pop(){
if(used==-1){
cout << "Error stack is empty";
return " ";
}
else{
used--;
return DynamicStack[used+1];
}
}
string& top () const{
if(used==-1){
cout << "Error stack is empty";
return " ";
}
else{
return DynamicStack[used];
}
}
bool isEmpty(){
return (used==-1);
}
int size(){
return (used+1);
}
int getCapacity(){
return Capacity;
}
private:
int Capacity; //How much the stack can hold
string* DynamicStack;
int used; //objects in the stack
};
And here are the errors:
SStack.h:11: error: expected unqualified-id before ‘int’
SStack.h:11: error: expected `)' before ‘int’
SStack.h:13: error: expected unqualified-id before ‘const’
SStack.h:13: error: expected `)' before ‘const’
SStack.h:14: error: expected class-name before ‘(’ token
SStack.h:25: error: ISO C++ forbids declaration of ‘operator+’ with no type
SStack.h:25: error: ISO C++ forbids declaration of ‘s2’ with no type
SStack.h:8: error: an anonymous union cannot have function members
SStack.h:31: error: abstract declarator ‘<anonymous class>’ used as declaration
SStack.cpp:11: error: expected unqualified-id before ‘int’
SStack.cpp:11: error: expected `)' before ‘int’
SStack.cpp:17: error: expected unqualified-id before ‘const’
SStack.cpp:17: error: expected `)' before ‘const’
SStack.cpp:21: error: expected class-name before ‘(’ token
SStack.cpp: In member function ‘std::string&<anonymous class>::pop()’:
SStack.cpp:33: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘const char*’
SStack.cpp: In member function ‘std::string&<anonymous class>::top() const’:
SStack.cpp:44: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘const char*’
SStack.cpp: At global scope:
SStack.cpp:8: error: an anonymous union cannot have function members
SStack.cpp:70: error: abstract declarator ‘<anonymous class>’ used as declaration
Your include guard has the same name as your class. Remember that the preprocessor is a very simplistic search/replace feature.
#define SStack
class SStack
{
public:
// Constructor
SStack( int cap);
becomes:
#define SStack
class
{
public:
// Constructor
( int cap);
One pattern is to name it the same as your header's filename, such as STACK_H.
First of all, as was already noted, the header guard is broken.
Now, onto the actual problems:
You have misunderstood how class definition works. Your header is largely correct, what is wrong is your .cpp file. You are redefining class that you already have defined inside the header file. The proper way to provide implementation of member function is this
void SStack::SStack(const SStack& s){
DyanmicStack = new string[cap];
} or in for clearer example:
void SStack::push(const string& s){
DynamicStack[used] = s;
used++;
}.
Basically, you have to prepend the classes's name before the function name.
Also, just by copy pasting this I've noticed typo in your code (see if you can spot it ;-) ), and I would recommend rethinking the design, even if it is just an exercise.
I realized the class Pila(stack) some times ago, this is my solution:
(sorry but I'm new.. so I don't know how to indent the code here)
file: pila.h
//nodo is the type of elements that class pila contains.
struct nodo
{
int dato;
nodo* precedente;
};
class pila
{
private:
nodo* ultimo;
public:
pila();
void push(int numero);
int pop();
};
file: pila.cpp
#include <iostream>
#include"pila.h"
using namespace std;
pila::pila()
{
ultimo=NULL; // punta all'ultimo nodo inserito
}
void pila::push(int numero)
{
nodo* nuovo;
nuovo=new struct nodo;
nuovo->dato=numero;
if(ultimo==NULL)
{
nuovo->precedente=NULL;
ultimo=nuovo;
}
else
{
nuovo->precedente=ultimo;
ultimo=nuovo;
}
}
int pila::pop()
{
if (ultimo==NULL)
{
return 0;
}
else
{
int prelevato=ultimo->dato;
ultimo=ultimo->precedente;
return prelevato;
}
}