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+’
asked Oct 5, 2012 at 18:15
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
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
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
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
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 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 (Все метки)
Как я могу это исправить?
__________________
0 |
marat_miaki 495 / 389 / 186 Регистрация: 08.04.2013 Сообщений: 1,688 |
||||
17.03.2020, 09:39 |
2 |
|||
const нельзя менять константную переменную, значит надо изменить до того как она станет константной Добавлено через 7 минут
camClient.println(«Content-Length: » + base64image.length());
вернее всего так
0 |
zarar384 1 / 1 / 0 Регистрация: 04.06.2017 Сообщений: 73 |
||||
17.03.2020, 10:19 [ТС] |
3 |
|||
marat_miaki, заранее спасибо за помощь. У меня жалуется на эту строчку
Ломаю голову уже второй день, никак не пойму
0 |
marat_miaki 495 / 389 / 186 Регистрация: 08.04.2013 Сообщений: 1,688 |
||||
17.03.2020, 12:32 |
4 |
|||
есть куча функции работы со строками в си https://prog-cpp.ru/c-string/ Добавлено через 19 минут
0 |
zarar384 1 / 1 / 0 Регистрация: 04.06.2017 Сообщений: 73 |
||||
17.03.2020, 13:05 [ТС] |
5 |
|||
marat_miaki, так?
0 |
495 / 389 / 186 Регистрация: 08.04.2013 Сообщений: 1,688 |
|
17.03.2020, 13:10 |
6 |
я не знаю что вернет
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,
Миниатюры
0 |
495 / 389 / 186 Регистрация: 08.04.2013 Сообщений: 1,688 |
|
17.03.2020, 18:15 |
9 |
Решениеzarar384, смущает запись 16 строки,
camClient.println(«Content-Length: » + (base64image.length() + image.length())); посмотрите 2 пост как писать, не уверен (нет практики) надо разбить
1 |
1 / 1 / 0 Регистрация: 04.06.2017 Сообщений: 73 |
|
17.03.2020, 20:11 [ТС] |
10 |
marat_miaki, спасибо!
0 |
01-07-2013
#1
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