I want to write a program that can get the number of each different characters in a sentence.But when I use gcc to compile my code,it shows errors like this:
error::expected unqualified-id before '[' token. And these errors happen in these lines:
CountMachine[cnt].ch=*(S.ch);
CountMachine[cnt].count++;
if(*(S.ch)==CountMachine[j].ch)
.....
(where I use CountMachine[]).
Here is my complete code:
CountChar.h:
typedef struct
{
char ch;
int count=0;
}CountMachine[50];
typedef struct
{
char *ch;
int length;
}HString;
CountChar.cpp(but I use C's syntax)
void CountChar(HString S)
{
int cnt=0;
for(int i=0;i<S.length;i++)
{
if(i==0)
{
CountMachine[cnt].ch=*(S.ch);
CountMachine[cnt].count++;
cnt++;
S.ch++;
}
else
{
for(int j=0;j<cnt;j++)
{
if(*(S.ch)==CountMachine[j].ch)
{
CountMachine[j].count++;
S.ch++;
break;
}
if(j==cnt-1)
{
CountMachine[cnt].ch=*(S.ch);
CountMachine[cnt].count++;
cnt++;
S.ch++;
}
}
}
}
printf("There are %d different characters.\n",cnt-1);
for(int m=0;m<cnt-1;m++)
{
printf("the number of character %c is %d",CountMachine[m].ch,CountMachine[m].count);
}
}
You declare CountMachine as a type which includes 50 structures containing a character and an integer in CountChar.h and then you address the type itself in CountChar.cpp.
You cannot address a specific item in a type, you need to either create a variable of type CountMachine or remove the keyword typedef from the declaration of CountMachine in the header.
You have a very fancy type alias that declares a CountMachine type, not a variable that contains an array of 50 unnamed structs.
typedef struct
{
char ch;
int count=0;
}CountMachine[50];
// CountMachine is a type (array 50 of unnamed struct)
// step-by step declaration is much more clear:
struct machine
{
char ch;
int count=0;
};
typedef struct machine machine_t;
machine_t machines[50];
// machines is a variable that holds an array of 50 machine_t
Related
I am trying to create an array in my UnsortedList class. I specified to create an array in the header file, and I also specified the MAX_SIZE, which is equal to 10. However, whenever I create my object of the class, the default constructor does not create that array with the MAX_SIZE. I am unsure what I am doing wrong. I also get an error saying "stack around the variable 'myList' was corrupted". Also, just as a side note, can I initialize the array values when the default constructor is called, instead of creating a function to do it?
"UnsortedList.h" header file:
#pragma once
class UnsortedList {
public:
UnsortedList();
bool IsFull(); //Determines whether the list is full or not (returns T or F)
int GetLength(); //Gets the length of the list
void SetListValues();
private:
int length;
const int MAX_ITEMS = 10;
int numbers[];
};
"UnsortedList.cpp" file:
#pragma once
#include "UnsortedList.h"
#include <fstream>
#include <iostream>
using namespace std;
UnsortedList::UnsortedList() {
length = 0; //sets length to 0
numbers[MAX_ITEMS]; //sets array maximum size to MAX_ITEMS (10 as indicated in UnsortedList.h)
}
bool UnsortedList::IsFull() {
return (length == MAX_ITEMS);
}
int UnsortedList::GetLength() {
return length;
}
void UnsortedList::SetListValues() {
ifstream inFile;
inFile.open("values.txt");
int x = 0;
while (!inFile.eof()) {
inFile >> numbers[x];
x++;
}
}
"main.cpp" file:
#include <iostream>
#include <string>
#include "UnsortedList.h"
using namespace std;
int main() {
UnsortedList myList;
myList.SetListValues();
return 0;
}
I recommend you use std::array or std::vector, but if you must use C arrays, then your definition in the header needs correcting:
class UnsortedList {
// ...
const static int MAX_ITEMS = 10;
int numbers[MAX_ITEMS];
};
You can remove the corresponding line in the constructor. The file reading method also needs correcting:
void UnsortedList::SetListValues() {
ifstream inFile;
inFile.open("values.txt");
int x = 0;
int read_value;
// x < MAX_ITEMS to avoid out of bounds access
while (x != MAX_ITEMS && inFile >> read_value)
{
numbers[x++] = read_value;
length++; // I assume you also want to increment the length at this point?
}
}
Edit: As noted by #πάνταῥεῖ, there is no good reason to use C style arrays when the standard provides std::array. Not much changes, it is declared as:
std::array<int, MAX_ITEMS> numbers;
You can use operator[] as with the C array. This is preferable as it provides a richer API and can be used like other C++ containers, i.e. with STL algorithms.
A program based on constructors
Error -Incompatible Type conversion from char to char[100]
Code -
#include<iostream>
using namespace std;
class demo
{
public:
char name[100];
//This is where char is declared
int marks;
demo()
{
marks = 0;
name = "Pro";
//assigning value to the char
cout<<"Working"<<endl;
}
void input()
{
cout<<"Enter Name and Marks"<<endl;
cin>>name>>marks;
}
void output()
{
cout<<name<<"\t"<<marks<<endl;
}
};
i tried putting name in 'name' and "name"
also i tried using type casting (char)
but it didnt seem to work
int main()
{
demo Obj1, Obj2;
//creating objects
Obj1.output();
Obj2.input();
Obj2.output();
return 0;
}
Arrays do not have the copy assignment operator.
So this statement in the constructor
name = "Pro";
is wrong.
You have to write
#include <cstring>
//...
std::strcpy( name, "Pro" );
Or a simpler way is just to rewrite the constructor like
demo() : name { "Pro" }, mark( 1 )
{
cout<<"Working"<<endl;
}
I am trying to loop through a struct array and initialize its member "history", an int array, to 0 (Undoubtedly, you'll have a better suggestion than the one-value-at-a-time loop, which will be welcome, but that's not what the question is about).
I get an error not only I do not understand, but I cannot see how the multiple internet posts about it come into a function within my case.
The error is:
In function 'int main()':....
|error: request for member 'history' in 'coin', which is of non-class type 'coin_t [10]'|
This is my code (true copy-paste from a new project):
#include <iostream>
using namespace std;
// Hand input parameters
const int coinCount=10;
int weight[coinCount]={11,11,9,10,10,10,10,10,10,10};
const int maxDepth=6;
const int caseCount=360;
// GLOBALS
struct coin_t
{
float w;
int history[maxDepth];
int curDepth;
};
coin_t coin[coinCount];
int main()
{
int i,j;
//Initialize coin struct array
for(i=0;i<coinCount;i++)
{
coin[i].w=weight[i];
coin[i].curDepth=-1;
for(j=0;j<maxDepth;j++) coin.history[j]=0; // Here's the error
}
}
coin is an array of struct coin_t with sized coinCount. You need to access by operator[] for the corresponding element in the array.
coin[i].history[j] = 0;
// ^^^
If you want to zero-initialize the history you could do better
struct coin_t
{
float w;
int history[maxDepth]{0};
// ^^^^
int curDepth;
};
by which you can skip the extra looping
for (j = 0; j < maxDepth; j++)
coin[j].history[j] = 0;
That being said C++ offers better std::array. Consider use if its suitable to the case.
I'm trying to pass a two-dimensional array to the numOfStudents function, but Visual Studio is giving me an error saying:
no instance of overloaded "numOfStudents" matches the argument list
I've been trying everything and I can't find a solution.
#include <stdio.h>
#include <cstring>
//Prototypes
int unsigned numOfStudents(char **namesArray, int *, FILE *);
void printArrays(char **namesArray, int *marksArray, int loopCounter);
int unsigned minMark(int);
int unsigned maxMark(int);
int unsigned averageMark(int);
//Two constants used later to create array of characters
const int MAX_SIZE = 10;
const int NAME_LENGTH = 30;
int main()
{
// Declaring array which will hold all names from file
char namesArray[MAX_SIZE][NAME_LENGTH];
int unsigned studentNumber = 0;
int loopCounter = 0;
int marksArray[MAX_SIZE]; //Array will hold the marks of students, it needs to be same size as the previous array
FILE *file; //creating pointer to a file
file = fopen("names.txt", "r"); //telling the pointer where the file is and how to access it
loopCounter = numOfStudents(namesArray, marksArray, file);
//System pause - will hold console window open
getchar();
return 0;
}
int unsigned numOfStudents(int *marksArray, char **namesArray, FILE *file)
{
char tempArrayName[50]; //Temporary array to hold names
char tempArrayLastName[50]; //Temporary array to hold last names
int i = 0; //Counter
bool stop = false;
if(file == NULL)
{
printf("\nFile has been not opened correctly\n");
}
else
{
while (stop == false)
{
//Reading the file in order to get 3 separate lines which are assumed as a single record of one student
fscanf(file, "%s\n%s\n%d", tempArrayName, tempArrayLastName, &marksArray[i]);
//Following lines are compying strings from temp arrays into main array and adding a space for better readability
strcpy(namesArray[i], tempArrayName);
strcat(namesArray[i], " ");
strcat(namesArray[i], tempArrayLastName);
//Chcecking if the sentinel value was read in order to stop the loop
stop = strcmp(tempArrayName, "****");
i++; //adding the counter
//Checking if file is too big, before program will crash with an internal error
if (i == MAX_SIZE)
{
printf("ERROR!!! FILE TOO BIG TO READ!");
stop == true;
}
}
}
return i;
}
You declare numOfStudents with this argument list:
int unsigned numOfStudents(char **namesArray, int *, FILE *);
But then you define it with a different argument list:
int unsigned numOfStudents(int *marksArray, char **namesArray, FILE *file)
Note that your declaration has the char** as the first argument, but your definition has it as the second argument (and the opposite for the int*). The ordering of the arguments is very important and must match exactly, so you need to change your definition to match the declaration:
int unsigned numOfStudents(char **namesArray, int *marksArray, FILE *file)
{
....
}
2D arrays can be a pain to pass around, why dont you use std::string and pass an array (or reference to std::vector) of them around?
int unsigned numOfStudents(char **namesArray, int *, FILE *); // declaration
int unsigned numOfStudents(int *marksArray, char **namesArray, FILE *file) // definition
Check the order of the parameters in each. The definition's second param is actually declaration's 1st param. You should be good if you rectify the order
You have defined the signature of function numOfStudents as:
int unsigned numOfStudents(char **namesArray, int *, FILE *);
and you declaring the function as :
int unsigned numOfStudents(int *marksArray, char **namesArray, FILE *file)
{
---*** Your Code Here ***---
}
This is the problem that the "sequence of calling parameter" of the signature of the function and the function declaration should be same as the passing parameter. So it should be like :
int unsigned numOfStudents(char **namesArray, int *marksArray, FILE *file)
{
---*** Your Code Here ***---
}
I am getting the above error during compilation:
Structure:
struct connection_handlers
{
int m_fd;
}
struct connection_handlers ** _queue;
int main()
{
_queue = (struct connection_handlers **) malloc ( 3* sizeof ( struct connection_handlers *)); //Allocating space for 3 struct pointers
for (i=0;i<3;i++)
{
_queue[i]->m_fd=-1;
}//Initializing to -1
//.....
//I assign this varaible to the file descriptor returned by accept and then
//at some point of time i try to check the same variable and it gives compilatio error.
for (i=0;i<3;i++)
{
if (_queue[i]->m_fd!=-1)
}//It give error at this line.
}
What could be the reason for error.
Thanks
Since you tagged this question both C and C++, here is what is wrong with your C++.
don't put struct inside your casts
don't use implicit int for your loop counters
struct declarations need a terminating ;
_queue is declared with a messed-up type
your last loop is missing
Once you clean that up it compiles fine.
#include <cstdlib>
struct connection_handlers {
int m_fd;
};
int main() {
connection_handlers** _queue = (connection_handlers**) malloc(3*sizeof (connection_handlers*));
for (int i=0;i<3;i++) {
_queue[i]->m_fd=-1;
}
for (int i=0;i<3;i++) {
if (_queue[i]->m_fd!=-1)
; // DOES NOTHING
}
}
_queue[i] is a connection_handlers *. You can't compare that to -1, which is an int. Did you mean to check _queue[i]->m_fd?