C++ error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] - c++

#include <iostream>
#include <string>
using namespace std;
float findSimilarityScore(string A, string B)
{
string C;
if (A.length() != B.length())
{
return -1;
}
if (A.length() == 0 and B.length() == 0)
{
return -1;
}
else
{
int i;
for (i = 0; A.length() - 1; i = i+1)
{
if (A[i] == B[i])
{
C.append(A[i]);
}
if (A[i] != B[i])
{
return 0;
}
}
cout << C << endl;
}
}
int main()
{
findSimilarityScore("DDS","DAS");
}
when i try to run my code, my IDE show this:
/home/ubuntu/workspace/hmwk4/hmwk4-1.cpp: In function ‘float findSimilarityScore(std::string, std::string)’:
/home/ubuntu/workspace/hmwk4/hmwk4-1.cpp:24:30: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
Why?
I want : if the first char in A is same to the first char in B, then add this char to the string C. if the second char in A is same to the second char in B, then add this char to the string C. And so on.

In the line
C.append(A[i]);
std::string::append has no overload that takes a single char. Use push_back instead:
C.push_back(A[i]);
This will fix your compilation error, but your function is still logically incorrect. It returns 0 the first time it finds any character that doesn't match between the two strings, and if the two strings are identical then it will invoke undefined behavior by reaching the end of a non-void function without returning a value.

string::append() with a single parameter is expecting a string argument, you are passing a single char. Try
C.append(1, A[i]);
Also, once you find a non-matching char, you return without printing the new string. Move the cout just before the return
if (A[i] != B[i])
{
cout << C << endl;
return 0;
}
And be sure to add a return at the end of your function in case you don't find any characters which are unequal.

Related

How can I fix my C++ program? The program is supposed to get the number of spaces in a string with a function

Code:
#include <iostream>
#include <string>
using namespace std;
/**
Gets the number of spaces in a string.
#param str any string
#return the number of spaces in str
*/
string count_spaces(string hi) {
int spaces;
for (int i = 0; i < hi.length(); i++) {
if (hi.substr(i, 1) == " ")
spaces +=1;
}
return spaces;
}
int main()
{
string str;
getline(cin, str);
cout << count_spaces(str) << endl;
return 0;
}
I'm not sure why I am getting this error in my C++ program. spaces is an int value in the program.
Error: helper_function.cpp: In function ‘std::string count_spaces(std::string)’:
helper_function.cpp:17:8: error: could not convert ‘spaces’ from ‘int’ to ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’}
17 | return spaces;
| ^~~~~~
| |
| int
I'm not sure how to go about solving it.
you need
int count_spaces(string hi)
instead of
string count_spaces(string hi)
Your count_spaces() function is declared to return a string instead of an int. You need to fix that:
int count_spaces(string hi)
Also, you need to initialize spaces, otherwise the code has undefined behavior when hi is empty since it will be returning an indeterminate value:
int spaces = 0;
Also, if (hi.substr(i, 1) == " ") can be simplified to if (hi[i] == ' '), and spaces +=1; simplified to ++spaces;.
Although, you should consider using the standard std::count() algorithm instead of counting characters manually:
#include <algorithm>
...
size_t count_spaces(string hi) {
return count(hi.begin(), hi.end(), ' ');
}

Counting blank spaces to get word count

I have a homework assignment in which I have to return the number of words in a string based on the number of blank spaces. Here is my code, I am not sure what is wrong with it but I keep getting error messages when I try to compile it.
string getWordCount(string sentence){
int count = 1;
for(int i = 1; i < sentence.length(); i++){
if (s[i]==' '){
count++;
}
}
return count;
}
The error messages are:
error: ‘s’ was not declared in this scope
if (s[i]==' '){
^
error: could not convert ‘count’ from ‘int’ to ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
return count;
^~~~~
To compile your code, you must ensure that return type (count is an int) is compatible with the declared return type of the function (you said it would return string). So instead of:
string getWordCount(string sentence)
declare your function as :
int getWordCount(string sentence)
Note also that you use s[i], but s is not declared. You probably mean sentence[i].
Consider also solving the different algorithmic errors mentionned in the comments (i.e. wrong result for an empty string, for a string with only blank, and depending on the exercise narative, for a string where several consecutive spaces are used between two words) to finish your homework and improve your skills.
You are passing in a variable named sentence but parsing on a variable named s. Also, count is an int but your return type is string. Try this:
int getWordCount (string sentence)
{
int count = 1;
for (int i = 0; i < sentence.length (); i++)
{
if (sentence[i] == ' ')
count++;
}
return count;
}
What they said.
Plus ...Avoid indexing with square brackets. Use range-based for loops. Be careful about trivial input (no words, or even an empty string, in this case). Do not assume that white space is only spaces, or that it only comprises one character. Input parameters that a function does not modify can be declared const-reference, to avoid making an un-needed copy. Use #include <algorithm> for common tasks.
SPOILER ALERT. Read no more until you after you have finished the assignment.
#include <cctype>
#include <string>
int get_word_count(const std::string &sentence)
{
int count = 0;
bool scanning_a_word = false;
for (auto ch : sentence) {
if (!std::isspace(ch)) {
if (!scanning_a_word) {
count += 1;
scanning_a_word = true;
}
} else {
scanning_a_word = false;
}
}
return count;
}
Bonus (and better) solution. The following does not use a state-variable (scanning_a_word). I call that kind of code "bread crumb programming". You leave bread crumbs along the trail to show where you've been. Sometimes birds eat the bread crumbs. Look Ma, no crumbs!
#include <algorithm>
int get_word_count(const std::string &sentence)
{
int count = 0;
auto next = sentence.begin();
const auto done = sentence.end();
while(done != next) {
next = std::find_if_not(next, done, std::isspace);
if (done != next) {
count += 1;
next = std::find_if(next, done, std::isspace);
}
};
return count;
}
Generally, when a variable is not declared within a scope you defined it inside something locally and it does not exist after that block of code (i.e. for loop) has finished executing. Or, you have not declared the variable at all.
error: ‘s’ was not declared in this scope
if (s[i]==' '){
^
Assuming you were trying to iterate through the parameter you passed in, which is a string called sentence, I either change the variable name to s of the parameter, copy the string into another string called s, or change s to sentence in the loop. The different variations are shown below:
// change parameter name to s
string getWordCount(string s)
{
int count = 1;
for(int i = 1; i < sentence.length(); i++)
{
if (s[i]==' ')
count++;
}
return count;
}
// change s to sentence inside the loop
string getWordCount(string sentence)
{
int count = 1;
for(int i = 1; i < sentence.length(); i++)
{
if (sentence[i]==' ')
count++;
}
return count;
}
// create a string s, and copy sentence into string s
string getWordCount(string sentence)
{
int count = 1;
string s = strcpy(s, sentence);
for(int i = 1; i < sentence.length(); i++)
{
if (s[i]==' ')
count++;
}
return count;
}
For your second error, generally this error occurs when there is an issue with casting a variable type to another type. In your case, the below error occurs because you are declaring a function will return a string, however, you are trying to return an int.
error: could not convert ‘count’ from ‘int’ to ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
return count;
^~~~~
To fix this error, simply change the return type to int. However, if you really want to return the count as a string for some reason, convert the integer to a string before returning. Both variations are shown below.
// Change return type to int to match count's type
int getWordCount(string sentence)
{
int count = 1;
...
...
return count;
}
// If you really need to send count back as a string for some reason, convert the int to string
string getWordCount(string sentence)
{
int count = 1;
...
...
return itoa (count);
}
Please note: this is only describing why your compilation errors are occurring and how to fix them so that you can continue on with your homework assignment. This is not describing what is wrong, logically, with your code.

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';

prefix calculator having trouble compilng

I am having some trouble with a program that is supposed to take a command line expression and interpret it as a normal mathematical expression.This is what I am getting as an error:
driver.cpp: In function ‘int main(int, char**)’:
driver.cpp:17:57: error: no matching function for call to‘PrefixCalculator::eval(std::istringstream)’
driver.cpp:17:57: note: candidate is:
PrefixCalculator.h:33:3: note: T PrefixCalculator::eval(std::istringstream&) [with T = int, std::istringstream = std::basic_istringstream]
PrefixCalculator.h:33:3: note: no known conversion for argument 1 from ‘std::istringstream {aka std::basic_istringstream}’ to ‘std::istringstream& {aka std::basic_istringstream&}’
I can't understand what the error is trying to suggest to me.
Any suggestions for fixing that? I'm going to add exceptions later, so they are commented out for now.
This is the code:
PrefixCalculator.cpp
#pragma once
#include <sstream>
using namespace std;
template<class T>
class PrefixCalculator {
public:
PrefixCalculator(void){
numOperator = 0;
numOperand = 0;
};
~PrefixCalculator(void){};
T eval(istringstream&);
int getNumOperator() {
return numOperator;
};
int getNumOperand() {
return numOperand;
};
private:
//if you feel you need private helper functions and/or helper data
int numOperator;
int numOperand;
};
template<class T>
T PrefixCalculator<T>::eval(istringstream& input) {
//this function needs to throw an exception if there's a problem with the expression or operators
char nextChar = input.peek();
//this while loop skips over the spaces in the expression, if there are any
while(nextChar == ' ') {
input.get(); //move past this space
nextChar = input.peek(); //check the next character
}
if(nextChar == '+') {
input.get(); //moves past the +
numOperator++;
return eval(input) + eval(input); //recursively calculates the first expression, and adds it to the second expression, returning the result
}
/***** more operators here ******/
if(nextChar == '-') {
input.get();
numOperator++;
return eval(input) - eval(input);
}
if(nextChar == '*') {
input.get();
numOperator++;
return eval(input) * eval(input);
}
if(nextChar == '/') {
input.get();
numOperator++;
return eval(input) / eval(input);
}
/****** BASE CASE HERE *******/
//it's not an operator, and it's not a space, so you must be reading an actual value (like '3' in "+ 3 6". Use the >> operator of istringstream to pull in a T value!
input>>nextChar;
T digit = nextChar - '0';
numOperand++;
return digit;
//OR...there's bad input, in which case the reading would fail and you should throw an exception
}
driver.cpp
#include <sstream>
#include <string>
#include <iostream>
#include "PrefixCalculator.h"
using namespace std;
int main(int argc, char** argv) {
PrefixCalculator<int> calc;
string expression;
cout << "Give a prefix expression to evaluate, or q to quit." << endl;
getline(cin,expression);
while(expression[0] != 'q') {
//try {
int result = calc.eval(istringstream(expression));
cout << result << endl;
//}
//catch { //will not compile, you have to finish this!
//
//}
cout << "Give a prefix expression to evaluate or q to quit." << endl;
getline(cin,expression);
}
return 0;
}
calc.eval(istringstream(expression)); passes a temporary instance to eval(), you'll need an lvalue.
Provide an extra variable for the stream
istringstream iss(expression);
and pass that one
int result = calc.eval(iss);

c++ returning and using char array pointers

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 ...