Error invalid operands of types const char and char to binary operator

Possible Duplicate: How do I concatenate multiple C++ strings on one line? According to this a C++ std::string is concatenated by using operator+. Why then does this code using namespace std;

Possible Duplicate:
How do I concatenate multiple C++ strings on one line?

According to this a C++ std::string is concatenated by using operator+.
Why then does this code

using namespace std;
string sql = "create table m_table(" + 
    "path TEXT," +
    "quality REAL," +
    "found INTEGER);"; 

cause this error?

invalid operands of types ‘const char [22]’ and ‘const char [17]’ to
binary ‘operator+’

Community's user avatar

asked Oct 5, 2012 at 18:15

jacknad's user avatar

1

What chris said, but in this particular case you can do

string sql = "create table m_table("
    "path TEXT,"
    "quality REAL,"
    "found INTEGER);"; 

Which will concatenate strings at compile time.

answered Oct 5, 2012 at 18:18

Michael Krelin - hacker's user avatar

5

You need to explicitly convert it to a string to match the argument list:

string sql = std::string("create table m_table(") + 
"path TEXT," +
"quality REAL," +
"found INTEGER);"; 

Now the first one is a string matched up with a const char[N], which matches one of the operator+ overloads and returns a new std::string, which is used to repeat the process for the rest.

answered Oct 5, 2012 at 18:16

chris's user avatar

chrischris

59.4k13 gold badges140 silver badges198 bronze badges

5

a better way is to use std::ostringstream

#include <sstream>

const std::string myFunc(const std::string& s1, const std::string& s2)
{
  std::ostringstream os;
  os<<s1<<" "<<s2;
  return os.str();
}

The advantage is that you can use the std::ostream << operator overloads to stringify non string values too

answered Oct 5, 2012 at 18:25

mohaps's user avatar

mohapsmohaps

9904 silver badges10 bronze badges

7

I am making an Arduino alarm. This is the error:

exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Here is the code that triggers it:

lcd.print("0"+hours+":"+minutes);

This code is similar, but worked before:

String none="00";
lcd.print(none+":"+none+":"+minutes);

I can post the full code if you need it. How can this be fixed?

asked Jun 12, 2016 at 2:16

starrynight234's user avatar

Your first code took a String object, then added other strings (note lowercase) to it — which are characters enclosed in quotes. It is legal to add strings to String objects.

Your new code doesn’t have any String objects at all — and you’re not allowed to add strings to strings (both lowercase).

It will work if you change your new code to:

lcd.print(String("0")+hours+":"+minutes);

That turns the original string "0" into a String object, and then adds more strings to it.

answered Jun 12, 2016 at 2:23

John Burger's user avatar

John BurgerJohn Burger

1,8251 gold badge9 silver badges23 bronze badges

zarar384

1 / 1 / 0

Регистрация: 04.06.2017

Сообщений: 73

1

16.03.2020, 23:40. Показов 4954. Ответов 9

Метки arduino (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (camClient.connect(postHost, postHttpPort))
    {
      uint8_t num = 1;
      String base64image = "id=7292&num=" + num + "&image=" + (base64::encode(fb->buf, fb->len));
 
      Serial.println("connection");
      camClient.println("POST /test/image/post.php HTTP/1.0");
      camClient.println("Host: cloud.***.com");
      camClient.println("Accept: */*");
      camClient.println("User-Agent: Mozilla/5.0");
      camClient.println("Content-Length: " + base64image.length());
      camClient.println("Content-Type: image/jpeg" );
      camClient.println();
     
      camClient.write(base64image.c_str());
 
      //Serial.println(base64_encode_expected_len(fb->len) + 1);
      //Serial.println(base64image.length());
      camClient.stop();
    }
    else {
      // if you didn't get a connection to the server:
      Serial.println("connection failed");
    }

Как я могу это исправить?
Error: invalid operands of types ‘const char*’ and ‘const char [8]’ to binary ‘operator+’

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



marat_miaki

495 / 389 / 186

Регистрация: 08.04.2013

Сообщений: 1,688

17.03.2020, 09:39

2

Цитата
Сообщение от zarar384
Посмотреть сообщение

const

нельзя менять константную переменную, значит надо изменить до того как она станет константной

Добавлено через 7 минут

Цитата
Сообщение от zarar384
Посмотреть сообщение

camClient.println(«Content-Length: » + base64image.length());

C++
1
2
camClient.print("Content-Length: ");
 camClient.println( base64image.length());

вернее всего так



0



zarar384

1 / 1 / 0

Регистрация: 04.06.2017

Сообщений: 73

17.03.2020, 10:19

 [ТС]

3

marat_miaki, заранее спасибо за помощь. У меня жалуется на эту строчку

C++
1
  String base64image = "id=7292&num=" + num + "&image=" + (base64::encode(fb->buf, fb->len));

Ломаю голову уже второй день, никак не пойму



0



marat_miaki

495 / 389 / 186

Регистрация: 08.04.2013

Сообщений: 1,688

17.03.2020, 12:32

4

есть куча функции работы со строками в си https://prog-cpp.ru/c-string/
и много функции у String описанные в справке Ардуины

Добавлено через 19 минут

C++
1
2
3
4
5
String stringOne, stringTwo;
 String base64image=String();
 stringOne = String("id=7292&num=");
  stringTwo = String("&image=");
  base64image =stringOne + num + stringTwo;



0



zarar384

1 / 1 / 0

Регистрация: 04.06.2017

Сообщений: 73

17.03.2020, 13:05

 [ТС]

5

marat_miaki, так?

C++
1
2
3
4
5
6
7
8
uint8_t num = 12;
      String stringOne, stringTwo, stringThree, stringFour;
      String base64image = String();
      stringOne = String("id=7292&num=");
      stringThree = String("&image=");
      stringFour = String(base64::encode(fb->buf, fb->len));
      stringTwo = String(num);
      base64image = stringOne + stringTwo + stringThree + stringFour;



0



495 / 389 / 186

Регистрация: 08.04.2013

Сообщений: 1,688

17.03.2020, 13:10

6

я не знаю что вернет

Цитата
Сообщение от zarar384
Посмотреть сообщение

base64::encode(fb->buf, fb->len)

Если 6 строка прокатит, проверяйте …



0



1 / 1 / 0

Регистрация: 04.06.2017

Сообщений: 73

17.03.2020, 13:11

 [ТС]

7

marat_miaki, нет, base64image.length() выдает 0. Без base64::encode(fb->buf, fb->len) никак



0



zarar384

1 / 1 / 0

Регистрация: 04.06.2017

Сообщений: 73

17.03.2020, 14:07

 [ТС]

8

marat_miaki,
Вроде все нормально, но через http port ничего не передается

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
if (camClient.connect(postHost, postHttpPort))
    {
      uint8_t num = 12;
      String stringOne, stringTwo;
      String image = String();
      stringOne = String("id=7292&num=");
      stringTwo = String("&image=");
      image = stringOne + num + stringTwo;
      String base64image = base64::encode(fb->buf, fb->len);
 
      //Serial.println("connection");
      camClient.println("POST /test/image/post.php HTTP/1.0");
      camClient.println("Host: cloud.***.com");
      camClient.println("Accept: */*");
      camClient.println("User-Agent: Mozilla/5.0");
      camClient.println("Content-Length: " + (base64image.length() + image.length()));
      camClient.println("Content-Type: image/jpeg" );
      camClient.println();
      camClient.write((image + base64image).c_str());
      
      //Serial.println(base64_encode_expected_len(fb->len) + 1);
 
      camClient.stop();
    }
    else {
      // if you didn't get a connection to the server:
      Serial.println("connection failed");
    }

Миниатюры

invalid operands of types 'const char*' and 'const char [8]' to binary 'operator+'
 



0



495 / 389 / 186

Регистрация: 08.04.2013

Сообщений: 1,688

17.03.2020, 18:15

9

Лучший ответ Сообщение было отмечено zarar384 как решение

Решение

zarar384, смущает запись 16 строки,

Цитата
Сообщение от zarar384
Посмотреть сообщение

camClient.println(«Content-Length: » + (base64image.length() + image.length()));

посмотрите 2 пост как писать, не уверен (нет практики) надо разбить
на 2 строки кода даже три отдельно просчитать и переменная =base64image.length() + image.length()
camClient.print(«Content-Length: «);
переменная =base64image.length() + image.length();
camClient.println( переменная);



1



1 / 1 / 0

Регистрация: 04.06.2017

Сообщений: 73

17.03.2020, 20:11

 [ТС]

10

marat_miaki, спасибо!



0



01-07-2013


#1

drazenmozart is offline


Registered User


invalid const char[] and char [] to binary operator+

hi to all!
i’m posting for the first time here and also i’m new to c++! So,excuse me a priori. I’m trying to open a file with ifstream like this:

Code:

std::ifstream      file("/home/alex/Desktop/csvDumps/"+event->name);

where ‘event’ is an inotify_event struct and ‘name’ is defined as char name[]; in this struct.

but i get : «error: invalid operands of types �const char [29]� and �char [0]� to binary �operator+�».

Tried to cast event->name by:

Code:

std::ifstream      file("/home/alex/Desktop/csvDumps/"+(const char)event->name);

but nothing went right.

Please help!
This code is in a while(1) loop and every time the name of the file to be opened changes. Any other idea for opening the file with an input variable like the one before is accepted!!

thanks in advance!!


Я пытаюсь создать таблицу с переменным количеством столбцов. YH (я, Y1, Y2 …. Yd)

Поэтому я создал цикл for внутри запроса. Но это показывает следующую ошибку —

  error: invalid operands of types ‘const char*’ and ‘const char [7]’ to
binary ‘operator+’
for(int l=1;l<=d;l++) {commandline+=", Y"+ l +" real ";}

Основной код приведен ниже —

string commandline;
commandline = "DROP TABLE YH";
if(SQL_SUCCESS != SQLExecDirect(hdlStmt, (SQLCHAR*)(commandline.c_str()), SQL_NTS))
{
cout<<"The drop YH table is unsuccessful."<<endl;
}

commandline = "CREATE TABLE YH""(i int primary key ";
for(int l=1;l<=d;l++) {
commandline+=", Y"+l+" real ";
}
commandline+=" ) ";
if(SQL_SUCCESS != SQLExecDirect(hdlStmt, (SQLCHAR*)(commandline.c_str()), SQL_NTS))
{
cout<<"The create table sql command hasn't been executed successfully."<<endl;
}

Я попробовал следующее —

для (int l = 1; l<= d; l ++) {командная строка + = «, Y» l «real»;}

для (int l = 1; l<= d; l ++) {командная строка + = «, Y» + std :: string (l) + «real»;}

Ни один из них, кажется, не работает.

1

Решение

Вы не можете использовать + объединить целое число в строку. Когда ты пишешь

", Y" + l

это добавляет l на указатель на строковый литерал, и это просто возвращает другой указатель. Затем, когда вы делаете + " real" он пытается добавить указатель на этот массив, но нет такой перегрузки для + оператор. + может использоваться только для объединения, когда хотя бы один из аргументов является std::string,

std::string(l) тоже не работает. Это не то, как вы получаете строковое представление числа. Функция, которую вы хотите std::to_string(l),

commandline += ", Y" + std::to_string(l) + " real ";

1

Другие решения

Альтернативный подход до C ++ 11:

Документация по std::ostringstream

В двух словах, ostringstream позволяет вашей программе записывать в самоизменяющийся буфер, который легко преобразуется в string так же, как вы записываете в любой другой поток ввода. подобно cout, например.

// create the ostringstream around the initial string data
ostringstream commandline("CREATE TABLE YH (i int primary key ");
for(int l=1;l<=d;l++) {
// write into the ostringstream. l will automatically be converted from a number
commandline << ", Y" << l <<" real ";
}
commandline << " ) ";

// (str() gets the string from the ostringstream.
// c_str() converts this string into a character array
if(SQL_SUCCESS != SQLExecDirect(hdlStmt, (SQLCHAR*)(commandline.str().c_str()), SQL_NTS))
{
cout<<"The create table sql command hasn't been executed successfully."<<endl;
}

0

Понравилась статья? Поделить с друзьями:
  • Error invalid number of arguments for encryption
  • Error invalid new expression of abstract class type
  • Error invalid module instantiation
  • Error invalid method declaration return type required java
  • Error invalid mailbox перевод