Unintelligible error code for sorting program - c++

I wrote a program in c++ which is supposed to print how many time a certain letter is contained in a word. So I used a 2-D arrays which is kinda new to me, i get 3 error codes which I don't really understand. Thanks for your help!
#include <iostream>
#include <cstring>
void check(char wArr[], int letter[], char search[], std::string word);
int main(int argc, char const *argv[]) {
//int letter[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
char search[26][2] = {{'a', 0},{'b', 0},{'c', 0},{'d', 0},{'e', 0},{'f', 0},{'g', 0},{'h', 0} ,{'i', 0} ,
{'j', 0},{'k', 0},{'l', 0},{'m',0} ,{'n',0} ,{'o',0},{'p',0},{'q',0},{'r',0},{'s',0},{'t',0},
{'u', 0},{'v', 0} ,{'w',0},{'x',0},{'y', 0},{'z', 0}};
std::string word;
std::cout << "Please enter the word: \n";
std::cin >> word;
char wArr[word.length()];
strcpy (wArr, word.c_str ());
check(wArr, search, word);
return 0;
}
void check(char wArr, char search[][2], std::string word){
for(int s = 0; s < 26; s++) {
for ( char i = 0; i < word.length(); i++) {
if(wArr[i] == search[s][1]) {
search[s][2]++;
}
}
}
for (int t = 0; t < 26; t++) {
if(search[t][2] > 0){
std::cout << search[t][1] << ": " << search[t][2] << '\n';
}
}
}
Error codes:
/home/julian/workspace-atom/countletter/main.cpp: In function ‘int main(int, const char**)’:
/home/julian/workspace-atom/countletter/main.cpp:16:33: error: cannot convert ‘char (*)[2]’ to ‘int*’ for argument ‘2’ to ‘void check(char*, int*, char*, std::__cxx11::string)’
check(wArr, search, word);
^
/home/julian/workspace-atom/countletter/main.cpp: In function ‘void check(char, char (*)[2], std::__cxx11::string)’:
/home/julian/workspace-atom/countletter/main.cpp:24:34: error: invalid types ‘char[char]’ for array subscript
if(wArr[i] == search[s][1]) {
^

The error is pretty clear. Your function prototype has different types for arguments compared to the actual definition:
void check(char wArr[], int letter[], char search[], std::string word);
vs
void check(char wArr, char search[][2], std::string word)
The second error is due to an attempt to use wArr as an array while it's been declared as char.

Related

Why I cant use atoi() function on a "string" instead of the char pointer in C++?

I tried the following code and it is giving me error.
int main() {
string String = "1235";
int num = atoi(String);
cout << num << endl;
return 0;
}
/*
error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'
int num = atoi(String);
^
mingw32-make.exe[1]: *** [Debug/main.cpp.o] Error 1
mingw32-make.exe: *** [All] Error 2
*/
But if I use the following code it works perfectly fine.
int main() {
char* String = "1235";
int num = atoi(String);
cout << num << endl;
return 0;
}
//prints out 1235
I know I can solve my problem using stoi() function.
int main() {
string String = "1235";
int num = stoi(String);
cout << num << endl;
return 0;
}
//prints out 1235
I can solve my problem by using a char pointer instead of string. But I just want to know why this can't be done by placing string itself into atoi(). How does atoi() work internally?
I just wanna know how does atoi() function work in C++
Because const char* and std::string are incompatible, the implicit conversion
cause error.
If you still want to use std:string:
int main() {
string String = "1235";
int num = atoi(String.c_str());
cout << num << endl;
return 0;
}
see this ref.
While std::stoi accepts std::string as input, ::atoi does not.
Note: std::string is a c++ class type, const char* is a basic data type. Although std::string does have a member function .c_str(), which can return its C-Style representation with const char* type.
Protype declarations of std::stoi in <string>:
int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
int stoi( const std::wstring& str, std::size_t* pos = nullptr, int base = 10);
Protype declaration of ::atoi in <stdlib.h>:
int atoi (const char *__nptr);

c++ error: cannot convert basic_string<char>}' to 'const char*' for argument '1' to 'long int strtol

I'm new to C++, been programming a while in C though.
Trying to read in a string and then convert the string into int by using strtol.
Iam using the gcc compiler.
And I get the following error message: "c++ error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'const char*' for argument '1' to 'long int strtol(const char*, char**, int)' int c = strtol(str[j], &p, 10);".
I have tried different types of conversions but really like the strtol for future reference. Is there something to do with my vector string?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
using std::string;
int main()
{
int a = 0;
int i = 0;
int size = 0;
int* big;
cin>>a;
size = a*2;
int sizes[size];
string *str = new string[size];
while(i < a){
cin>>str[i];
i++;
}
i = 0;
while(i < a){
cout << str[i] << endl; // just for checking
i++;
}
for (int j =0; j<size-1;j++){
char* p;
char* q;
int c = strtol(str[j], &p, 10);
if (!*p) {
sizes[j] = *p;
}else{
sizes[j] = *p/2;
}
}
return 0;
}
Thanks in advance!
You can use strtol(str[j].c_str(), &p, 10); the call to c_str() returns a const char* that points at the contents of the string object, and strtol wants a const char*. Or you can write more idiomatic code, and call std::stol(str[j]).

passing a char ** to a function(const char **) in C++

I am trying to use the function rrd_update_r of the round robin database.
int rrd_update_r(const char *filename,const char *_template,
int argc,const char **argv);
The function accepts the as 3rd and 4th argument the well known argc, argv.
Even though I am using C++ (and g++) for this project, rrd is written in C and consequently I could use the function wordexp(char *, wordexp_t*) provided in GNY/Linux to split the arguments of a string into an argv array.
The problem is that wordexp_t returns a member of char ** type (as argv), which is incompatible apparently with the rrd_update_r function call.
/usr/include/rrd.h:238:15: error: initializing argument 4 of ‘int rrd_update_r(const char*, const char*, int, const char**)’ [-fpermissive]
To my surprise I could find no help on the matter either. This Why can't I convert 'char**' to a 'const char* const*' in C? solution did not work.
So I am left wondering: how can I pass the char ** into const char ** ?
The full function is
#include <errno.h> // Error number definitions
#include <rrd.h>
#include <wordexp.h>
void splitToArgs(string& parametersString) //parametersString contains space separated words (parameters).
{
wordexp_t we;
int er = 0;
if ( (er=wordexp(parametersString.c_str() , &we, 0)) != 0)
{
cout << "error in word expansion " << er << endl;
}
else
{
if (we.we_wordc>0)
{
char * filename = we.we_wordv[1]; //filename is part of the parameters string
rrd_clear_error();
int ret = rrd_update_r( filename , NULL , we.we_wordc, we.we_wordv );
if ( ret != 0 )
{
cout << "rrd_update error # = " << ret << " error string = " << rrd_get_error() ;
}
}
}
wordfree(&we);
}
This use of const_cast (if correct) also does not work
error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]
const char **w = const_cast<char**>(we.we_wordv);
const_cast<const char**>(whatever)
is the correct way to const_cast in this case.
Im going to give you an example passing a char to a enum ( which is in fact a constant )
enum TIngrediente
{
TOMATE,
QUESO,
NATA,
CEBOLLA,
POLLO,
HUEVO,
SALAMI,
ANCHOA,
BACON,
GAMBA
};
string tolower(string s)
{
string r = s;
for (int i = 0; i < s.size(); ++i)
r[i] = tolower(r[i]);
return r;
}
TIngrediente StrToIngrediente(string s)
{
s=tolower(s);
int i;
while (i < INGREDIENTES.size() and INGREDIENTES[i] != s)
++i;
return (TIngrediente)i;
}
Now the only thing you need to do is make another function changing again from const char to char ( very easy)
This way youll trans form the char constant to a const char, be ware youll need to add a library, cctype and local to make this work.

Having problems with cstring arrays

I am having trouble with my code with something with arrays. I am getting the following errors
In function ‘int main(int, const char**)’:
75: error: cannot convert ‘char*’ to ‘char (*)[81]’ for argument ‘1’ ion(char (*)[81], OneItem*, int&, int&)’
In function ‘void parseInformation(char (*)[81], OneItem*, int&, in
164: error: ISO C++ forbids comparison between pointer and integer
166: error: incompatible types in assignment of ‘const char [2]’ to
169: error: ISO C++ forbids comparison between pointer and integer
174: error: ISO C++ forbids comparison between pointer and integer
174: error: ISO C++ forbids comparison between pointer and integer
176: error: invalid conversion from ‘char*’ to ‘char’
The code doesn't line up with the line numbers. I have tried multiple things googled some things still haven't found a solution.
const int MAX_CHARACTERS = 80;
const int MAX_INVENTORY = 12;
typedef char OneLine[MAX_CHARACTERS + 1];
struct OneItem
{
char product[MAX_CHARACTERS + 1];
int quantity;
float unitPrice;
float totalPrice;
};
int main( const int argc, const char* argv[] )
{
OneLine fileName;
ifstream inFile;
OneLine readLine;
OneItem inventory[MAX_INVENTORY];
int readLineIndex;
int structureCounter = 0;
int averageQuantity;
float averagePrice;
float averageTotalPrice;
displayIntroduction();
getFileName( argc, argv, fileName );
if (!inFile)
{
cout << "File not found: " << fileName << endl;
}
else
{
inFile.open(fileName);
while(!inFile.getline(readLine, MAX_CHARACTERS, '\n').eof())
{
if (structureCounter < MAX_INVENTORY)
{
parseInformation(readLine,inventory, readLineIndex, structureCounter);
}
}
void parseInformation(OneLine readLine[],OneItem inventory[], int & readLineIndex, int & structureCounter)
{
int tempIndex = 0;
int valueCounter = 0;
OneLine tempArray;
while(readLine[readLineIndex] != '\n')
{
tempArray = "\0";
while(readLine[readLineIndex] == ' ')
{
readLineIndex += 1;
}
while(readLine[readLineIndex] != ' ' && readLine[readLineIndex] != '\n')
{
tempArray[tempIndex] = readLine[readLineIndex];
tempIndex += 1;
readLineIndex += 1;
}
if(valueCounter == 0)
{
for(int i = 0; i <= strlen(tempArray); i++)
{
inventory[structureCounter].product[i] = tempArray[i];
}
valueCounter += 1;
}
else if(valueCounter == 1)
{
inventory[structureCounter].quantity = atoi(tempArray);
valueCounter += 1;
}
else
{
inventory[structureCounter].unitPrice = atof(tempArray);
structureCounter += 1;
}
}
return;
Your definition of parseInformation is wrong. It says that readLine should be an array of OneLine, but it only wants a single OneLine. It should be:
void parseInformation(OneLine readLine,OneItem inventory[], int & readLineIndex, int & structureCounter)
This is causing all the errors you're getting, because you're calling the function with a single OneLine, not an array. And inside the function you're comparing readLine[readLineIndex] with a character, which requires readLine to be an array of characters, not an array of OneLine.
The OneLine typedef makes this an array already, you didn't need to add [] to the parameter declaration.
As Barmar said you need to change first argument, but there is one more problem, here:
OneLine tempArray;
while(readLine[readLineIndex] != '\n')
{
tempArray = "\0";
You cannot make such assign. tempArray needs to be of type const char* or you need to make it this way:
tempArray[some_index] = '\0';

expected primary-expression before ‘const’ errors

Please help. I am getting many errors.
sub2.cpp: In function ‘int main()’:
sub2.cpp:11:14: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
sub2.cpp:12:14: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
sub2.cpp:16:17: error: expected primary-expression before ‘const’
sub2.cpp:16:36: error: expected primary-expression before ‘const’
sub2.cpp:11:6: warning: unused variable ‘outer’ [-Wunused-variable]
sub2.cpp:12:6: warning: unused variable ‘inner’ [-Wunused-variable]
make: * [sub2] Error 1
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
char *Subtract(const char *outer, const char *inner);
int main()
{
char outer = "Bookkepper";
char inner = "keep";
char *word = new char[50];
word = Subtract(const char &outer, const char &inner);
cout << word << endl;
return 0;
}
char *Subtract(const char *outer, const char *inner)
{
int olen = strlen(outer);
int first_occ_idx = -1;
for(int i=0; i < olen; i++){
if(strncmp(outer+i, inner,strlen(inner)) == 0){
first_occ_idx = i;
}
}
if(first_occ_idx == -1){
return NULL;
}
int ilen = strlen(inner);
int xx = olen - ilen;
char *newstr = new char[xx];
int idx = 0;
for(int i=0; i < first_occ_idx; i++){
newstr[idx++] = outer[i];
}
for(int i=first_occ_idx+ilen; i < olen; i++){
newstr[idx++] = outer[i];
}
newstr[idx] = '\0';
return newstr;
}
In C++, string literals like "Bookkepper" (sic) are const character pointers, it's a little stricter than in C. So it should be:
const char *outer = "Bookkeeper"; // Note also spelling
rather than:
char outer = "Bookkepper";
In addition, you don't include types when calling a function, so:
word = Subtract(const char &outer, const char &inner);
would be better as:
word = Subtract(outer, inner);
Separately (and these are style suggestions only), the correct type for things that represent sizes (such as number of characters in a string) is size_t rather than int.
And it's usually considered good form to clean up all your dynamic memory explicitly so, before returning from main(), you could put:
delete[] word;