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;
Related
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.
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]).
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.
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';
Here is my code:
#include<stdio.h>
#define MAXLINE 100
/*print the reverse of the input*/
int getline1(char line[], int maxline);
char *reverse(char);
main(){
int len;
char line[MAXLINE];
char *rp;
while ((len = getline1(line, MAXLINE)) > 0)
rp = reverse(line);
printf("%s", *rp);
return 0;
}
int getline1(char s[], int lim){
int c, i;
for (i = 0; (c=getchar()) != EOF && c != '\n'; i++)
if (i > lim-1)
continue;
else
s[i] = c;
if (c == '\n'){
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
char *reverse(char ca[]){
int i;
int i1 = 0;
char *rp;
char reversed[MAXLINE];
for (i = MAXLINE-1; i >= 0; i--){
reversed[i1] = ca[i];
i1++;
}
rp = reversed;
return rp;
}
But when I try to compile it, I get the following errors:
reverse.cpp: In function ‘int main()’:
reverse.cpp:14:20: error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]
reverse.cpp:7:7: error: initializing argument 1 of ‘char* reverse(char)’ [-fpermissive]
reverse.cpp:15:19: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’ [-Wformat]
I don't have much experience with C++. What am I doing wrong? I just want to make a pointer to a char array and return it.
I just want to make a pointer to a char array and return it.
You appear to want to return a string. That is not a pointer to a char array. Even if your program compiled, you would invoke UB, as you return a pointer to an automatic object- and there are quite a few other runtime errors in your code as well. You got lucky that you also made a compile-time error so the compiler did not accept your program. This C++ program achieves what you intend:
#include <string>
#include <iostream>
std::string reverse(std::string val) {
return std::string(val.rbegin(), val.rend());
}
int main() {
std::string str;
while(std::getline(std::cout, str))
std::cout << reverse(str);
}
What am I doing wrong?
You're learning C89 intead of C++11. They're really different things.
If you wish to learn to code C++, you must learn std::string, and the rest of the Standard library. You will not get anywhere with char*, char[], and MAGIC_BUFFER_SIZE.
You first declare the function prototype
char *reverse(char);
But the actual function is declared as
char *reverse(char ca[])
That's your problem.
What are you trying to achieve ? There are logical errors in the code ...
while ((len = getline1(line, MAXLINE)) > 0)
rp = reverse(line);
printf("%s", *rp);
this part will call reverse on every /n character but printf will never be called...
Also you have string of 100 chars and your reverse will put leading char on end of reverse string.. so if you have string of 5 chars you will have garbage on first 95 positions and then 5 chars you need ...