I have some error can anyone help me in this - c++

error: incompatible types in assignment of 'std::__cxx11::string' {aka'std::__cxx11::basic_string<char>'} to 'char [100]'
error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'
and I got the above two errors for these lines of codes
string s1=asctime(localtime(&timetoday));;
string r=s1.substr(4,6);
ch=r; //char ch[100];(defined aleady)
//1st error was in line just above this comment
if(strcmp(r,"Dec 20")==0)
//2nd error was in line just above this comment
{
cout<<"made my first try for creating this program";
}
else if(strcmp(r,"Dec 21")==0)
{
cout<<"Shortest day of the year";
}
I'm trying to create a simple remainder program in C++ using code blocks.

The problem is in the following line:
ch = r;
The variable ch is of type char[100], the variable r is of type std::string. These types are not compatible, you cannot assign an std::string to a char array.
You probably want to write the following instead:
strcpy( ch, r.c_str() );
However, it would be simpler not to use C-style strings at all, and instead use std::string everywhere, like this:
string s1=asctime(localtime(&timetoday));;
string r=s1.substr(4,6);
if( r == "Dec 20" )
{
cout<<"made my first try for creating this program";
}
else if( r == "Dec 21" )
{
cout<<"Shortest day of the year";
}
Another mistake in your program seems to be that you are calling strcmp twice, once like this:
strcmp(r,"Dec 20")
And once like this:
strcmp(ch,"Dec 21")
The second one is correct, but the first one is wrong, as you must pass a C-style string (a char array), and not a C++ style string (a std::string). You probably meant to write ch instead of r. Alternatively, if you want to keep using r, you can write r.c_str() instead, which will return a C-style string. But, as already stated above, the best solution would probably be to use std::string everywhere and not use strcmp at all, as it is only intended for C-style strings.

The code is incomplete, i.e. ch is not defined, but you probably want to use r.c_str() in the first call to strcmp, and in the 2nd case r.c_str() instead of ch.

strcmp compares two cstrings(const char*), you are passing a std::string. try something like ``if(r == "Dec 20") ...```

ch = r you are mixing string with char array or c with cpp . Why not make your life easy you can use std::copy in this way
std::copy(r.begin(),r.end(),ch);
Happy Coding.

The variable ch is of kind char[100], the variable r is of kind std::string. These sorts are not compatible, you can not assign an std::string to a char array

Related

Why do I have to make a 2d array for this

I was solving a question online on strings where we had to perform run-length encoding on a given string, I wrote this function to achieve the answer
using namespace std;
string runLengthEncoding(string str) {
vector <char> encString;
int runLength = 1;
for(int i = 1; i < str.length(); i++)
{
if(str[i - 1] != str[i] || runLength == 9)
{
encString.push_back(to_string(runLength)[0]);
encString.push_back(str[i - 1]);
runLength = 0;
}
runLength++;
}
encString.push_back(to_string(runLength)[0]);
encString.push_back(str[str.size() - 1]);
string encodedString(encString.begin(), encString.end());
return encodedString;
}
Here I was getting a very long error on this particular line in the for loop and outside it when I wrote:
encString.push_back(to_string(runLength));
which I later found out should be:
encString.push_back(to_string(runLength)[0]);
instead
I don't quite understand why I have to insert it as a 2D element(I don't know if that is the right way to say it, forgive me I am a beginner in this) when I am just trying to insert the integer...
In stupid terms - why do I gotta add [0] in this?
std::to_string() returns a std::string. That's what it does, if you check your C++ textbook for a description of this C++ library function that's what you will read there.
encString.push_back( /* something */ )
Because encString is a std::vector<char>, it logically follows that the only thing can be push_back() into it is a char. Just a single char. C++ does not allow you to pass an entire std::string to a function that takes a single char parameter. C++ does not work this way, C++ allows only certain, specific conversions betweens different types, and this isn't one of them.
And that's why encString.push_back(to_string(runLength)); does not work. The [0] operator returns the first char from the returned std::string. What a lucky coincidence! You get a char from that, the push_back() expects a single char value, and everyone lives happily ever after.
Also, it is important to note that you do not, do not "gotta add [0]". You could use [1], if you have to add the 2nd character from the string, or any other character from the string, in the same manner. This explains the compilation error. Whether [0] is the right solution, or not, is something that you'll need to figure out separately. You wanted to know why this does not compile without the [0], and that's the answer: to_string() returns a std::string put you must push_back() a single char value, and using [0] makes it happen. Whether it's the right char, or not, that's a completely different question.

Comparing element in string with length-1 string in C++

I am sorry for the simple question, but I cannot understand why this simple program does not work.
What is a[0] supposed to be other than "a"?
#include <iostream>
using namespace std;
int main(){
string a = "abcd";
string b = "a";
if (a[0]==b){//<------problem here
cout << a << endl;
}
return 0;
}
which returns the error
no match for ‘operator==’ (operand types are ‘char’ and ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’)
or simply using string c=a[0]; returns the error:
conversion from ‘char’ to non-scalar type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ requested
PS: after trying a few things, I can get it to work if I compare a[0]==b[0] or assign c[0]=a[0] because those are now definitely the same type, but I still would like to know what the standard and/or fastest way to carry out a comparison of a substring with another string in C++ is.
You should use std::string::find to find substrings. Using the subscript operator on string returns a single character (scalar), not a string (vector, non-scalar); therefore, they are not the same type and there is no defined comparison.
You can can also use std::string::substr to select a substring which you can directly compare against another string.
Example
#include <iostream>
#include <string>
int
main() {
std::string a = "abcd";
std::string b = "a";
if (a.find(b) != std::string::npos) {
std::cout << a << "\n";
}
if (a.substr(0, 1) == b) {
std::cout << a << "\n";
}
return 0;
}
References
http://en.cppreference.com/w/cpp/string/basic_string/find
http://en.cppreference.com/w/cpp/string/basic_string/substr
http://en.cppreference.com/w/cpp/string/basic_string
what is a[0] supposed to be other than "a"?
It is an 'a' not "a" and it is a char. You cannot compare a char to a string because they are different types. But what you can do is extract a substring from your string that is the length of 1 character:
if (a.substr(0,1)==b)...
Then you will be comparing "a" to "a" because .substr returns a string not a char, even if the length is 1.
Also don't forget to #include <string> if you are working with std::string.
a[0] is a character, which has the value 'a', whereas b is a string, which has a different type. This will work if an operator ==(char, string) is defined (or some variant with const's and/or ref's) but there isn't, at least in the C++ standard, so the compilation should fail. The clang compiler even gives the helpful message,
invalid operands to binary expression ('int' and 'string'...
which indicates that you're comparing different types.
Try changing it to compare a[0] and b[0]. The bracket operator is defined for strings, and returns a character, so you can compare them that way.
edit: This may look as if it doesn't answer the question. It does answer the original question; the OP changed the entirety of the question after the fact (and someone added a corresponding answer) but the original question is still there in the first paragraph. I'll delete the answer if moderators want.

C++ if statement not registering "-f" as a possible value

Hey so recently I tried getting a C++ program of mine to take in a parameter "-f" (it helps create a file of data that the user can enter), and so I tried the typical if statement:
if (argv[1] == "-f") { cout << "Please input a file name:" << endl;}
But unfortunately, it doesn't seem to work. The code is registering that "-f" is an argument to add to argc, it just doesn't want to check that it's properly "-f". I even tried atoi to change "f" to 102 and check it via an integer, but it just doesn't seem to be working. Thank you for your time!
argv[1] == "-f" is a pointer comparison. It will never be true because a command line argument will never have the same address as a string literal in your program.
Try if (strcmp(argv[1], "-f") == 0) instead.
Both argv[something] and -f are C-style strings which decay (in most cases) to a pointer to the first character of that string.
Hence a simple comparison, unlike the std::string type, will not work since it will be comparing two distinct pointers. If you want to compare C-style strings, strcmp and its brethren are the way to go.
Otherwise you can turn both those values into actual C++ strings and use the equality operator to compare them.
I'd opt for the former:
if (strcmp (argv[1], "-f") == 0) {
argOneIsMinusF();
}

Issues with declaring and writing to arrays with Arduino and C++

I'm messing around with an Arduino board for the first time.
I have an array declared like this (I know don't judge me), it's for storing each character of the LCD as a sort of cache:
char* lcd_characters[] = {"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};
Then later on I'm trying to write to a specific slot of the array, like this, to save that letter to it:
new_char = String(message.charAt(i));
...blah blah blah...
lcd_characters[pos] = new_char; << error here
However it is giving me this error:
error: cannot convert 'String' to 'char*' in assignment
The funny thing is when I do this (below) it do assign the letter to it, however I have a var which is a single letter but can't assign it.
lcd_characters[pos] = "H";
Can someone help me out please. Thanks. I'm brand new to C and been ok so far.
Basically I want an array of characters and then I want to write on the array positions with a new value.
Why does it even matter what type of string I'm writing to that array position, I should be able to write a number or boolean there too and call it later. Is there something wrong with the way the array is declared initially?
Edit:
I tried...
lcd_characters[pos] = new_char.c_str();
however that's giving me the similar error:
invalid conversion from 'const char*' to 'char'
Wtf? All I want to do is say this array position equals this new value. That's it. I've done this a million times in javascript, ruby, python (even php) etc. I just want to go, this array... x[12] equals my letter in new_char !!!! Ahh.
A few remarks:
Are you using C or C++? String is a C++ class, but you are creating a an array of c strings (char *).
You are creating an array of strings (char* var[] equals to char**), but your naming suggests you want an array of characters. A c string is basically an array of characters, so stick with that (char * or char []).
I would recommend you go for only C code in this case:
char lcdChars[4] = {' ', ' ', ' ', ' '}; // init with spaces
lcdChars[2] = 'x'; // write x to position 3
Note: A string in C++ can output a C string (char *) by calling stringInstance.c_str().

Char to Int in C++? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to convert a single char into an int
Well, I'm doing a basic program, wich handles some input like:
2+2
So, I need to add 2 + 2.
I did something like:
string mys "2+2";
fir = mys[0];
sec = mys[2];
But now I want to add "fir" to "sec", so I need to convert them to Int.
I tried "int(fir)" but didn't worked.
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
Alright so first a little backround on why what you attempted didn't work. In your example, fir is declared as a string. When you attempted to do int(fir), which is the same as (int)fir, you attempted a c-style cast from a string to an integer. Essentially you will get garbage because a c-style cast in c++ will run through all of the available casts and take the first one that works. At best your going to get the memory value that represents the character 2, which is dependent upon the character encoding your using (UTF-8, ascii etc...). For instance, if fir contained "2", then you might possibly get 0x32 as your integer value (assuming ascii). You should really never use c-style casts, and the only place where it's really safe to use them are conversions between numeric types.
If your given a string like the one in your example, first you should separate the string into the relevant sequences of characters (tokens) using a function like strtok. In this simple example that would be "2", "+" and "2". Once you've done that you can simple call a function such as atoi on the strings you want converted to integers.
Example:
string str = "2";
int i = atoi(str.c_str()); //value of 2
However, this will get slightly more complicated if you want to be able to handle non-integer numbers as well. In that case, your best bet is to separate on the operand (+ - / * etc), and then do a find on the numeric strings for a decimal point. If you find one you can treat it as a double and use the function atof instead of atoi, and if you don't, just stick with atoi.
Have you tried atoi or boost lexical cast?