Error : Invalid conversion from char to const char * - c++

I am facing this problem from day 1.
Actually, the book I am reading from has this program written in this way, but when I check it practically on Eclipse IDE, it does not work properly, always showing this error:
invalid conversion from char to const char *
Although I know what the issue is, I don't know how to resolve this problem, and I am facing this problem with every program in which there is some string operation.
The error is with this if statement:
if(!strcmp(str, *ptr[i]))
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const char *ptr[10] = { "books", "television", "computer", "sports" };
int i = 0;
char str[25];
cout << "\nEnter your favorite leisure pursuit here :" << "\n";
cin >> str;
for (i = 0; i < 4; i++)
{
if (!strcmp(str, *ptr[i]))
{
cout << "\n your favorite pursuit is available here " << endl;
break;
}
}
if (i == 4)
{
cout << "\n\nYour favorite leisure is not available here" << endl;
}
return 0;
}

strcmp() compares two null-terminated const char* strings. But, you are trying to compare a null-terminated char[] string to a single char, hence the error. This is because you are dereferencing the 2nd const char* string to access its 1st char element.
ptr is an array of const char* pointers, so you need to drop the extra * dereference operator when accessing ptr[i], so that you compare the whole string, not just a single character of the string, eg:
if (strcmp(str, ptr[i]) == 0)

Related

C++ storing an element of a string array into a variable

I am currently coding in C++ and am fairly new to it. I am running into issues with converting an element of an array of strings into a variable. The cout statement dcity[selection-1] works as intended. However, I am unable to store dcity[selection-1] into a variable named departureLocation. Visual Studios gives me the error that there is no suitable conversion function from a string to a char. Does anyone have advice on how to properly store this? Thanks!
int main()
{
int selection = 0;
char departureLocation;
std::string dcity[] = { "Seattle Detroit Seattle Chicago Houston Seattle" };
std::cout << "Please choose a number from the list";
std::cin >> selection;
std::cout << dcity[selection-1];
departureLocation=dcity[selection-1]
};
Since C++ is a strongly-typed language, it doesn't like type mismatches.
You've declare your variable in the following way:
char departureLocation;
This means departureLocation is a variable of type char, or a single character. So 'C' can go into departureLocation but "Chicago" cannot, as it is more that one character.
You've also declared your array like so:
std::string dcity[] =
Here, you have defined the type of the array as std::string. So elements of the array are strings, not chars.
The short answer is that you need to change the type of departureLocation to a string when you declare it, instead of a char. Something like:
std::string departureLocation;
I also didn't see any include statements in your code above. For C++ to recognize the string class, you'll need to make sure the following is at the top of your code somewhere:
#include <string>
dcity is an array of std::strings. departureLocation is a char which can only hold one character. To store (copy) an element of the array dcity, departureLocation must be of type std::string (or any other type that can be constructed fron a std::string):
std::string dcity[] = { "Seattle Detroit Seattle Chicago Houston Seattle" };
std::string departureLocation = dcity[0];
Be aware thet dcity is an array consisting of only one element. Maybe you want an array where each city is a seperate array element:
std::string dcity[] = { "Seattle", "Detroit", "Seattle",
"Chicago", "Houston", "Seattle" };
std::string departureLocation = dcity[2];
std::cin >> selection;
std::cout << dcity[selection-1];
Also you should do some error checking before using user input as an array index:
if (!(std::cin >> selection) || selection < 1 || selection > sizeof(dcity) / sizeof(*dcity)) {
std::cerr << "Input error!\n";
return EXIT_FAILURE;
}
std::string departureLocation = dcity[selection - 1];
If you don't need independent copies of your array elements you could also use a reference to std::string:
std::string &departureLocation = dcity[selection - 1];
Be aware that changes to the string using departureLocation will now reflect on the array element departureLocation references. If you don't want to allow changes, use a const reference:
std::string const &departureLocation = dcity[selection - 1];
First of all the compiler thinks that there is only one element in the array because arrays in c++ should have commas between each element and each string must be enclosed inside double quotes.The second error is that you are trying to save data of type string into a variable having data type char.
Code
#include<string>
#include<iostream>
using namespace std;
int main()
{
int selection=0;
string depaturelocation;
string dcity[]={"Seattle","Detroit","Seattle","Chicago","Houstan","Seattle"};
int size=sizeof(dcity)/sizeof(dcity[0]);
for(int i=0;i<size;i++)
{
cout<<i+1<<" : "<<dcity[i]<<endl;
}
cout<<"please enter the destination no:";
cin>>selection;
for(int i=0;i<size;i++)
{
if(selection-1==i)
{
depaturelocation=dcity[i];
}
}
cout<<"destination:"<<depaturelocation;
return 0;
}
Your code needs little modification.
1. An array is initialized by giving its component values separated by a comma. Note each individual element should be of the same type as that of the declared array.
2. The C++ is very strict with the type matching. We can assign objects only of the same type. In the above code, a string object is being assigned to a character variable which is against the rule. A C string is an array of characters terminated by null character (\0). In C++, string is more advanced and it is an object which has very useful member function. For e.g. to get length of the string, just say obj.length(). We need to have character array since in string there can be more than one char element. We need to have c-string of the string object to get into an array of characters. Please see below the modified code.
#include <iostream>
#include <cstring>
#include <string>
using namespace std; //std:: is not required in front of cout
int main()
{
int selection = 0;
string dcity[] = { "Seattle", "Detroit" ,"Seattle", "Chicago", "Houston","Seattle" };
cout << "Please choose a number from the list";
cin >> selection;
cout << dcity[selection-1] << endl;
char departureLocation[dcity[selection-1].length()+1];
strcpy(departureLocation,dcity[selection-1].c_str());
cout << departureLocation;
// cout << *c;
return 0;
}
You could to store the selection in a std::string, because char can only store a single character. Be also careful of where you access your array to not go out of bounds (what happens if somebody enters 1000 etc.) and that non-programmer users index lists starting with 1. You can try this code:
#include <iostream>
#include <string>
int main()
{
const auto Cities = { "Seattle", "Detroit", "Seattle", "Chicago", "Houston", "Seattle" };
std::cout << "Please choose a number from the list (1-" << Cities.size() << "): ";
int selection = 0;
std::cin >> selection;
if (selection < 1 || selection > Cities.size()) {
std::cout << "\ninvalid selection!\n";
return -1;
}
const std::string departureLocation = *(Cities.begin() + selection - 1);
std::cout << "\nyou selected: " << departureLocation;
return 0;
};

Using pointers to find positions of characters between unbalances parentheses

I am given a C++ programming problem: In a string I need to find wether or not there are balanced parentheses. If not, using pointers I should find position of the characters between unclosed parentheses (between second opening and nearest closing).
The problem statement is a bit confusing, I know. I think it should work somehow like that:
Input #1:
((aba)aaab)
Output:
OK.
Input #2:
(aa(a)ab
Output:
Parentheses not balanced: between characters 1 and 6.
Code below solves part of problem with the closed parentheses check and also there is a structure to keep the address of the opening parenteses. I am not sure how exactly to use pointers for that purposes, some attempts did not give any result, so I need some help here.
#include<iostream>
#include<string>
#include<stack>
using namespace std;
struct br_data{
char br_t;
char *cptr; //store the address of the opening parenthesis
};
int main (){
string input;
int addr;
br_data br;
getline(cin, input);
stack<br_data> braces;
char *a = input[0];
auto init_char = static_cast<void*>(&a); //store the address of the first character in the input string
cout << static_cast<void*>(&a) << endl; //gives the address in memory
for(auto c: input) {
if (c == '(') {
br.br_t = c;
br.cptr = &c; //storing the address of the first parenhesis
braces.push(br);
} else if (c == ')' ) {
if (braces.empty())
cout << "This line does not contain unclosed parentheses\n";
if (!braces.empty())
braces.pop();
}
}
if (!braces.empty()){
//int addr = br.cptr;
cout << "This line does not contain unclosed parentheses\n";
//int pos = (&br.cptr) - (&a); //how to calculate the position??
cout << "Position of the second opening parenthis is " << () << endl;
//cout << "Position of the nearest closing parenthis is " << -how?? (static_cast<void*>(&br.cptr)) << endl;
}
if (braces.empty()){
cout << "Parentheses are balanced in this line\n";
}
return 0;
}
When you write
br.cptr = &c; //storing the address of the first parenhesis
you're actually storing the address of a local object of char type declared earlier:
auto c: input
By the moment you exit the loop it is officially dangling.
One simplest solution would be to actually consider string's characters, not their local copies:
for(auto &c: input) {
(and, even better, change auto into char for better clarity keeping source length the same). Then you can go on and see how your solution needs to be fixed further.
(A few extra free advice: input[0] is a rvalue reference of type char so it makes no sense to assign it to a variable of type char *, and what you try to do in that line is actually written as char *a = input.c_str(); or input.data() or even &input[0], pick the best option; and br.cptr is of type pointer-to-char already, so the character's position in a string would be calculated as br.cptr - a, you need to subtract the pointers themselves, not their addresses.)
#include <iostream>
using namespace std;
int main(){
char str[]="Hello Programming";
char *ptr;
char ch;
char s;
s='n';
ptr=str;
cout<<"To be found Character"<<endl;
cin>>ch;
while(*ptr++ != '\0')
if(*ptr==ch)
s='y';
if (s=='y')
cout<<"FOUND";
else
cout<<"not found";``
return 0;
}

ISO C++ forbids comparison between pointer and integer[-fpermissive] in C++ code

There is a problem with my code. It always return an error ISO C++ forbids comparison between pointer and integer[-fpermissive]. Can you help me see what is the problem here and how to solve it?
#include <iostream>
using namespace std;
char x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}
#include <iostream>
char is not a string, it is a character, means an integer (signed between -128 and 127 on most compiler implementations)
If you change the type of x to string it will do what you want
You had a raw C comparison char vs char * which explains the error message
By turning the char into a string you activate the string::operator== which accepts char * as a convenience and performs a string comparison, which is intuitively what you want to do.
My advice is: keep going with C++ and never use char *, malloc or all that C stuff likely to fail, stick to std::string, and use std::string::c_str() to get the string contents as const char * for use with C primitives if needed.
A positive side-effect is that it will avoid the trap of comparing 2 char * types with == operator, which compare pointers and not values.
using namespace std;
string x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}

Invalid conversion char to char* - Copying char in string array to another string array

I'm a beginner in C++ Programming language. I wanted to write a program that take the alphabets in a string array called str, and copy it in a new array called str_alpha.
And the same goes to numbers, the program copies it from str array to str_digit array.
There's my humble code, it might be full of errors and stuff. But this is what I could do now with my very little experience.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
using namespace std;
char str[100], str_alpha[100], str_digit[100];
int main()
{
gets(str);
for (int i=0 ; str[i] ; i++)
{
if (isalpha(str[i]))
{
strcpy (str_alpha[i] , str[i]);
}
else if (isdigit(str[i]))
{
strcpy (str_digit[i] , str[i]);
}
}
cout << "Alpha is " << str_alpha << endl ;
cout << "Number is : " << str_digit << endl ;
return 0;
}
And it gives my those errors :
F:\C++Progs\string\main.cpp||In function `int main()':|
F:\C++Progs\string\main.cpp|18|error: invalid conversion from `char' to `char*'|
F:\C++Progs\string\main.cpp|18|error: initializing argument 1 of `char* strcpy(char*, const char*)'|
F:\C++Progs\string\main.cpp|18|error: invalid conversion from `char' to `const char*'|
F:\C++Progs\string\main.cpp|18|error: initializing argument 2 of `char* strcpy(char*, const char*)'|
F:\C++Progs\string\main.cpp|22|error: invalid conversion from `char' to `char*'|
F:\C++Progs\string\main.cpp|22|error: initializing argument 1 of `char* strcpy(char*, const char*)'|
F:\C++Progs\string\main.cpp|22|error: invalid conversion from `char' to `const char*'|
F:\C++Progs\string\main.cpp|22|error: initializing argument 2 of `char* strcpy(char*, const char*)'|
||=== Build finished: 8 errors, 0 warnings ===|
Help me please.
Thanks in advance.
First of all, strcpy copies C strings (character arrays) not chars. Additionally, the lines strcpy(str_digit[i],str[i]) and strcpy(str_alpha[i], str[i]) would still probably be wrong even if this wasn't the case. Since you haven't initialised the arrays str_digit and str_alpha, you'll get a lot of garbage values while printing them and if any of those garbage values happen to be 0x00, the cout statements will fail to print the whole string. As already mentioned, you really should be using std::string rather than char[] or char*. Having said that, here are corrected versions of your code for both char[] and std::string.
Using gets is bad practice and you might consider using std::cin instead. And you might want to use an iterator rather than a simple for loop.
//using char[]
#include <iostream>
using namespace std;
int main()
{
char str[100] , str_alpha[100] , str_digit[100] ;
int alpha_counter=0, digit_counter=0;
cin.get(str, 99);
for (int i=0 ; str[i] ; i++)
{
if(isalpha(str[i]))
{
str_alpha[alpha_counter] = str[i];
alpha_counter++;
}
else if (isdigit(str[i]))
{
str_digit[digit_counter] = str[i];
digit_counter++;
}
}
str_alpha[alpha_counter] = 0;
str_digit[digit_counter] = 0;
cout << "Alpha is " << str_alpha << endl ;
cout << "Number is : " << str_digit << endl ;
return 0;
}
And the version using std::string:
//using std::string
#include <iostream>
using namespace std;
int main()
{
string str, str_alpha , str_digit;
cin >> str ;
for (string::iterator it = str.begin();it<str.end();it++)
{
if(isalpha(*it))
{
str_alpha += *it;
}
else if (isdigit(*it))
{
str_digit += *it;
}
}
cout << "Alpha is " << str_alpha << endl ;
cout << "Number is : " << str_digit << endl ;
return 0;
}
Both versions compile without warnings on g++ 4.2.1 with -Wall and -pedantic.
I'm a beginner in C++ Programming language.
The do not use char* and the likes; use C++ predefined types for this, in your case string:
string str;
cin >> str;
string alpha;
string digit;
for (unsigned int i = 0; i < str.length(); ++i) {
char chr = str[i];
if (isalpha(chr))
alpha.push_back(chr);
else if (isdigit(chr))
digit.push_back(chr);
}
Furthermore, strcpy is, as the name says, used to copy strings, not individual chars. You can copy those directly by assigning them. No function call needed.
The problem is that strcpy is intended to copy a whole string. In this case, you're copying individual characters, not entire strings. For individual characters, you can use a simple assignment.
There are a few other things to deal with though. First of all, you have:
char str[100];
outside any function. That defines an array of 100 char's, and initializes all of them to 0. You then loop through that, trying to find characters that are classified as alphabetical or digits -- which will never happen, because a zero byte ('\0', not '0') is never either one.
In fact, as far as a I can tell, you don't need str at all. What you (apparently) want is roughly like:
for (i in 0 to 127)
if (alpha(i))
add i to str_alpha
else if (digit(i))
add i to str_digit
As Konrad Rudolph already pointed out, you'd probably be much better off making str_digit and str_alpha into std::string's than arrays of char. Arrays can do the job, but they'll be more work to get really correct.
strcpy copies a whole string. Use plain assignment (= operator) for copying characters.
You're copying characters over, even though strcpy is designed to copy over strings (arrays of characters). The compiler is therefore complaining because you're supplying 'char' rather than 'char *'. If you're copying characters over then just do:
str_alpha[i] = str[i];

I am trying to return a Character Array but, I'm only getting the first letter returned

I'm working on a small little thing here for school. After hours of researching, and a ton of errors and logic reworking I've almost completed my little program here.
I'm trying to take user input, store it into the string, get a character array from the string ( dont ask why, I just have to put this into a character array ), then get the reversed order of the phrase that the user entered. Here is my code:
#include "stdafx.h"
#include <iostream>
#include <String>
#include <cstring>
using namespace std;
using namespace System;
#pragma hdrstop
char* getCharArray(string);
string reversePhrase( int, char* );
void main(void)
{
string sPhrase = "";
int sSize = 0;
string sReversed = "";
char* cPhrase = NULL;
cout << "Welcome to the You Type It & We'll Reverse it! [Version 1.0] " << endl;
cout << "This program will reverse your phrase, and count how many characters are in it!" << endl;
cout << "To begin just enter a phrase." << endl;
cout << "Enter a phrase: ";
getline( cin, sPhrase);
sSize = sPhrase.length();
cout << endl;
cPhrase = getCharArray(sPhrase);
sReversed = reversePhrase( sSize, cPhrase );
cout << sReversed;
system("pause");
}
string reversePhrase(int size , char* cPhrase)
{
string sReversed = "";
int place = size;
for ( int i = 0; i < size ; i ++ )
{
sReversed.append(1, cPhrase[place]);
cout << "Current string: " << sReversed << endl;
cout << "Current character: " << cPhrase[place] << endl;
place--;
}
return sReversed;
}
char* getCharArray(string sPhrase)
{
int size = 1;
size = sPhrase.length();
char* cArray = NULL;
cArray = new char[size];
for (int i = 0 ; i < size ; i++)
{
cArray[size] = sPhrase.at(i);
}
return cArray;
}
When I type in "ownage" into the program, this is what I get returned:
It is almost like my Character Array is getting garbage collected before it can use all of the characters. This is probably an easy fix but, I just don't see how I can get around this one.
Try rewriting getCharArray like this
char* getCharArray(string sPhrase)
{
int size = 1;
size = sPhrase.length();
char* cArray = NULL;
cArray = new char[size+1]; // NOTE
for (int i = 0 ; i < size ; i++)
{
cArray[i] = sPhrase.at(i); // NOTE
}
}
cArray[size]=0; // NOTE
return cArray;
}
Note that the assignment in the loop now uses the index variable. Also, you need to allocate one extra char in the array to set the null terminator for the string and then you need to set it at the end.
You'll also need to think about deallocating the array at some point
The bug is in this line:
cArray[size] = sPhrase.at(i);
That size should be your loop index.
You should probably look at using std::string more, and not poke around with character arrays when there's no need to.
Why use a char array at all? It's not only useless – it complicates the code substantially (the usage of your function is more difficult, and you've forgotten to free the memory allocated by new!). Why not just have the following function:
string reverse(string const& input);
(Passing the argument by const reference instead of by value saves you a copy!)
In fact, implementing the function only takes a single line using the features of the string class (one of its constructors takes two iterators):
string reverse(string const& input) {
return string(input.rbegin(), input.rend());
}
reversePhrase is also not correct. Try something like this:
string reversePhrase(int size , char* cPhrase)
{
string sReversed = "";
sReversed.resize(size);
int place = size - 1;
for ( int i = 0; i < size ; i ++ )
{
sReversed [i] = cPhrase[place];
cout << "Current string: " << sReversed << endl;
cout << "Current character: " << cPhrase[place] << endl;
place--;
}
return sReversed;
}
First, start the array with -1. After that, use a for loop with -1 and increment inside the loop. Then, you can get the first element of the array.