This question already has answers here:
invalid conversion from ‘const char*’ to ‘char’
(2 answers)
Closed 6 years ago.
I'm new to Arduino and C++. I wanted to make a program which will read input from a serial port. However there seem to be some problems when I try to compile it.
The error message that I am receiving is:
invalid conversion from const char* to char
Here is my code:
#define nombreBouteille 10
#define nombreCocktail 8
String cocktail[nombreCocktail][nombreBouteille][2];
String bouteille[nombreBouteille];
int serialValue;
void loop() {
if (Serial.available() > 0)
int serialValue = Serial.read();
if (serialValue == '1') {
readBouteille();
readCocktail();
}
}
//Read and set the bottles content
void readBouteille() {
for( int i = 0; i < nombreBouteille; i++) {
bouteille[i] = Serial.readStringUntil(" ");
}
}
//Read the cocktail
void readCocktail() {
for( int i = 0; i < nombreCocktail; i++) {
for ( int j = 0; j < nombreBouteille; j++) {
cocktail[i][j][0] = Serial.readStringUntil(" ");
cocktail[i][j][1] = Serial.parseInt();
}
}
}
readStringUntil takes a single char parameter to specify a delimiter, not a C string (const char *). So change:
bouteille[i] = Serial.readStringUntil(" "); // wrong: " " is a `const char *`
to:
bouteille[i] = Serial.readStringUntil(' '); // right: ' ' is a `char`
and similarly for the other call to readStringUntil.
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 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';
I have records coming in from fgets (web data using popen(), not a file) that are in const char * array format.
const char * cstr = buff;
The 3rd item is a string and needs to either be removed or changed to a zero.
How do I access the 3rd element in a const char * array stream in increments of 5?
1
2
string
4
5
1
2
string
4
5
code:
while(fgets(buff, sizeof buff, fp) != NULL)
{
const char * cstr2 = buff;
for(int i = 0; i < 5; ++i){
if(i == 3){
if (!strcmp(cstr2, "Buy\n")) {
printf("Found One!\n");
cstr2[2] = 0;
}
if (!strcmp(cstr2, "Sell\n")) {
printf("Found Two!\n");
cstr2[2] = 0;
}
}
}
}
expected output:
1
2
0
4
5
1
2
0
4
5
error:
no match and :
error: assignment of read-only location '*(cstr2 + 2u)'
How do you correctly access the 3rd element in a char streaming char array?
This solution was previously posted by anonymous:
char* getmyData()
{
char buff[BUFSIZ];
FILE *fp = popen("php getMyorders.php 155", "r");
if (fp == NULL) perror ("Error opening file");
size_t size = 1000;
char* data = (char*)malloc(size);
char* ptr = data;
std::string::size_type sz;
int i=0;
while(fgets(buff, sizeof(buff), fp) != NULL)
{
const char * cstr2 = buff;
const char* test = ptr;
//for(int i = 0; i < 5; ++i)
{
if(i == 2){
if (!strcmp(cstr2, "Buy\n")) {
printf("Found One!\n");
strcpy(ptr,"0\n");
//ptr+=2;
}
else
if (!strcmp(cstr2, "Sell\n")) {
printf("Found Two!\n");
strcpy(ptr,"0\n");
//ptr+=2;
}
else
{
strcpy(ptr,cstr2);
ptr+=strlen(cstr2);
}
}
else
{
strcpy(ptr,cstr2);
ptr+=strlen(cstr2);
}
try
{
int nc = std::stod (test,&sz);
std::cout << "Test: " << 1+nc << "\n";
}
catch(...)
{
}
i++;
if (i==5)
i=0;
}
if (ptr-data+100>=size)
{
int ofs = ptr-data;
size*=2;
data = (char*)realloc(data,size);
ptr = data+ofs;
}
}
return data; // DONT FORGET TO call free() on it
}
From your sample code it is not clear what is the expected output. Is it an array of integer ? a formatted text string ? a byte array ? we can't know.
Assuming you have a text formatted input and want a text formatted output, a simple solution is to write a new string with the correct values and not try to modify your input buffer.
If you know the exact format of your input records you could use fscanf to do the parsing instead of doing it by hand. And you could use ssprintf to do the formatting of the output string.
As others pointed out, if you can use C++, you'd have safer/easier options. Please comment about your willingness to use C++.
I am having the following problem with my code, though it compiles correctly:
value type const char cannot be used to initialize an entity of type char*
Can someone help me? I can run the code which is weird but I can't create a makefile using this. It's very weird to me.
int SpliString(struct dict_word *entry, const char *str)
{
long word_length,j,k;
int yearIndex;
char *buffer;
char *endOfYears;
char *endOfYear;
char *endOfDefinition;
char *endOfWord = strstr(str, "_#_");
//Sets the first num bytes of the block of memory pointed by ptr
//to the specified value (related as an unsigned char)
memset(entry, 0, sizeof(struct dict_word));
// If '_#_' is not found, it's NULL
if (endOfWord)
{
// Calculating word legth; 'str' points to start of word, 'endofWord' points to '_#_' that is just after word
word_length = endOfWord - str;
// Copying data into the word
strncpy(entry->words, str, word_length);
// 'endOfYears' points to '_#_,' but wee need to find follow '_#_'
// therefore there is added 3 in order to skip curremnt '_#_
endOfYears = strstr(endOfWord+3, "_#_");
if (endOfYears)
{
word_length = endOfYears - (endOfWord+3);
// Skips _#_
buffer = endOfWord+3;
yearIndex = 0;
j = 0;
// Finds next year in the line, it stops if all 10 years is filled
// or end of years string is reached
while(yearIndex<10 && buffer+j<endOfYears)
{
// Stores year in the buffer, with converting 'stirng' to 'int'
entry->year[yearIndex] = atoi(buffer+j);
// check year for negative...
if (entry->year[yearIndex]<=0)
return 0;
// Locating substring; 'j' is current offset from beginning of buffer
endOfYear = strchr(buffer+j, '_');
if (endOfYear)
{
j = endOfYear - buffer;
j++;
yearIndex++;
}
else
{
break;
}
}
//endOfYears points to '_#_' that separatates 'years' and 'definition'
//and there is needed to find '_#_' between 'definition' and 'synonyms'
//therefore it skips '_#_' that separatates 'years' and 'definition',
//+3, because '_#_' has length = 3
endOfDefinition = strstr(endOfYears+3, "_#_");
if (endOfDefinition)
{
word_length = endOfDefinition - (endOfYears+3);
k = 0;
for(j=0; j<word_length; j++)
{
// Skips '_#_'
if (endOfYears[j+3]==',')
{
entry->eng_synonyms[k] = ' ';
k++;
}
else if (endOfYears[j+3]>='a' && endOfYears[j+3]<='z')
{
entry->eng_synonyms[k] = endOfYears[j+3];
k++;
}
else if (endOfYears[j+3]!='_')
{
return 0;
}
}
k = 0;
word_length = (str+strlen(str)) - (endOfDefinition+3);
for(j=0; j<word_length; j++)
{
if (endOfDefinition[j+3]==',')
{
entry->heb_synonyms[k] = ' ';
k++;
}
else if (endOfDefinition[j+3]>='A' && endOfDefinition[j+3]<='Z')
{
entry->heb_synonyms[k] = endOfDefinition[j+3];
k++;
}
else if (endOfDefinition[j+3]!='_')
{
return 0;
}
}
}
// Check for legality
// Check all symbols of 'entry->words'
// calculate length and supress warning
for(j=0;j<(int)strlen(entry->words);j++)
{
if (entry->words[j]<'a' || entry->words[j]>'z')
return 0;
}
return 1;
}
}
return 0;
}
Use
const char *buffer;
const char *endOfWord = strstr(str, "_#_");
Confident OP is compiling in C++.
// C
char *strstr(const char *s1, const char *s2);
// C++
const char* strstr(const char* s1, const char* s2);
char* strstr( char* s1, const char* s2);
See
Compile C app with Visual Studio 2012
How to compile and execute C program on Visual Studio 2012 for Windows 8?