i have a question about a simple c++ function.
This is my cpp file:
#include <string>
#include <iostream>
#include <stdio.h>
#include <ros/ros.h>
#include <json_prolog/prolog.h>
using namespace std;
using namespace json_prolog;
int main(int argc, char *argv[])
{
ros::init(argc, argv, "Knives");
Prolog pl;
char M[]="drawer";
cout<<M<<endl;
if(strcmp(M,"knife")==0)
{
string q= "rdfs_individual_of(M, 'http://knowrob.org/kb/knowrob.owl#TableKnife')";
PrologQueryProxy bdgs = pl.query(q);
cout<< endl;
for(PrologQueryProxy::iterator it=bdgs.begin(); it != bdgs.end(); it++)
{
PrologBindings bdg = *it;
cout << "Knives individuals= "<< bdg["M"] << endl;
}
cout<< endl<< endl;
}
if(strcmp(M,"drawer")==0)
{
string q= "rdfs_individual_of(M, 'http://knowrob.org/kb/knowrob.owl#Drawer')";
PrologQueryProxy bdgs = pl.query(q);
cout<< endl;
for(PrologQueryProxy::iterator it=bdgs.begin(); it != bdgs.end(); it++)
{
PrologBindings bdg = *it;
cout << "Drawer individuals= "<< bdg["M"] << endl;
}
cout<< endl<< endl;
}
return 0;
}
this code is connect with an xml file to parse it.
if i compile it works and i have no problems.
Now i have to change it,because i don't want to define the variable char M but i want to give it in input. the problem is that i change :
char M[]=....
with:
char M;
cin>>M;
i have a problem about the conversion from char to const char [-fpermissive]
how i can solve it?
try this:
std::string M;
cin >> M;
replace lines like this:
if(strcmp(M,"drawer")==0)
with this:
if (M == "drawer" )
Why did you change an array of chars (char M[] = ...;) to a single char (char M;)? Aside from the other answer suggesting using a std::string instead (which you should do), if you must use an array of char variables, you need to use std::unique_ptr<char> M(new char[100]) before use in std::cin (I've assumed 100 chars are enough to hold the input; change as necessary).
std::string M = "drawer";
cout<<M<<endl;
if(M.compare("knife") == 0)
{
// do whatever
}
You can also do:
if(M == "knife")
{
// do whatever
}
Unless you need to use C strings, why would you not use the standard library string? No reason to make life more difficult.
Related
Here's what I tried and it's not logical. First_num++ is just copying 2 numbers instead of the second number and so is the last_num++
How do I continue copying like that and cout them
I know I can just cout the thing in reverse because the output is the same.I can do that by reversing the count but the question wants me to exchange the characters one by one. Please help, thanks.
#include <iostream>
#include <cctype>
using namespace std;
void reverse_word(char character[]);
int main()
{
char characters[50];
reverse_word(characters);
return 0;
}
void reverse_word(char character[])
{
char temp1[2] = "\0";
char temp2[2] = "\0";
char first_num = 1;
char last_num = 1;
cout << "Enter a word to reverse first word last word second first second last and so on: ";
cin >> character;
for (int i=0;i<strlen(character)/2;i++)
{
strncpy(temp1, character, first_num);
first_num++;
strcpy(temp2 , &character[strlen(character)-last_num]);
last_num++;
}
for (int i = 0; i < strlen(character) / 2; i++)
{
cout << temp2;
cout << temp1;
}
}
You can use the build-in function of c++ reverse(begin, end) where the begin and end iterator are as parameter like below:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "String example";
reverse(str.begin(), str.end()); // outputs --> elpmaxe gnirtS
cout<<"\n"<<str;
return 0;
}
This is a short and fast solution , but if you want to get a more depth view you can apply some nice alogrithm .
You should cout the temp variables in the same for loop, not in a different one.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void LowerCharacters(string& text);
void OutPutEachLetter(string text, int* ptr);
void comparePointers();
int main() {
string text1, text2; bool isAnagrams = true;
int *ptr1=NULL, *ptr2=NULL;
cout<<"Please enter first string ";
getline(cin,text1);
cout<<"Please enter second string ";
getline(cin,text2);
LowerCharacters(text1);
LowerCharacters(text2);
OutPutEachLetter(text1, ptr1);
OutPutEachLetter(text2, ptr2);
for(int i =0; i<26;i++) {
if (ptr1[i] != ptr2[i]) {
isAnagrams = false;
}
}
if(isAnagrams)
cout<<"These two strings are anagrams";
else
cout<<"These two strings are not anagrams";
delete []ptr1; delete []ptr2;
ptr1=NULL; ptr2=NULL;
}
void LowerCharacters(string& text) {
for (int i = 0; i < text.length(); i++) {
text[i]=tolower(text[i]);
}
}
void OutPutEachLetter(string text, int* ptr){
ptr = new int[26];
*ptr = {0};
for(int i =0;i<text.length()-1;i++)
{
ptr[text[i]-'a']++;
}
for(int j=0;j<26;j++){
if(ptr[j]!=0){
cout<<ptr[j]<<"\t"<<char(j+'a')<<endl;
}
}
}
Above was my code. I thought it would have worked but it did not. it printed the ptr1 successfully but never printed the ptr2. I want to know why... Any help will be appreciated!
I am kind of new to pointer stuff, I just wanted to try my best to use the pointer in my code so that I can practice more. I know that I can totally just create two static arrays in the main part and then write the array in my function OutputEachLetter as an argument and use the pass as a reference like int &arr. However, I really want to know why is my current code wrong and why am I not allowed to use this kind of code.
You could just do a little effort by adding algorithm library plus you're using C++, take some benefits of it. Just use the transform() for conversion of strings into lower case, and sort them then see if they're equal or not.
Everything could be done in a simplified way.
Consider the written program:
#include <iostream>
#include <algorithm>
int main(void) {
std::string str1, str2;
std::cout << "Enter the first string: ";
std::getline(std::cin, str1);
std::cout << "Enter the second string: ";
std::getline(std::cin, str2);
/* --- this --- */
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
transform(str2.begin(), str2.end(), str2.begin(), ::tolower);
std::sort(str1.begin(), str1.end());
std::sort(str2.begin(), str2.end());
if (str1 == str2)
std::cout << "Both strings are anagrams";
else
std::cout << "No anagrams";
std::cout << std::endl;
return 0;
}
hi guys so my question is how to convert a char array to a string. here is my code:
#include<iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol,256);
cout << lol << endl;;
}
return 0;
}
so I want to convert lol to a string variable like "stringedChar" (if thats even english lol)
so I can do stuff like:
string badwords[2] = {"frick","stupid"};
for (int counter = 0; counter < 2;counter++) {
if(strigedChar == badwords[counter]) {
bool isKicked = true;
cout << "Inappropriate message!\n";
}
}
Sorry im just a c++ begginer lol
Do something like this :
as char lol[128];
into string like: std::string str(lol);
Line : cin.getline(lol,256); <--> should be changed to cin.getline(lol,128)
Just invoke std::getline() on a std::string object instead of messing about with a char array, and use std::set<std::string> for badwords as testing set membership is trivial:
#include <iostream>
#include <set>
#include <string>
static std::set<std::string> badwords{
"frick",
"stupid"
};
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (badwords.count(line) != 0) {
std::cout << "Inappropriate message!\n";
}
}
return 0;
}
Note that this tests whether the entire line is equal to any element of the set, not that the line contains any element of the set, but your code appears to be attempting to do the former anyway.
First off, you have a mistake in your code. You are allocating an array of 128 chars, but you are telling cin.getline() that you allocated 256 chars. So you have a buffer overflow waiting to happen.
That said, std::string has constructors that accept char[] data as input, eg:
#include <iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol, 128);
string s(lol, cin.gcount());
cout << s << endl;;
}
return 0;
}
However, you really should use std::getline() instead, which populates a std::string instead of a char[]:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
getline(cin, lol);
cout << lol << endl;;
}
return 0;
}
How to apply find_first_of function for char (char array). I know it can be done for a string but I want to know how to do it when I can declare only variable of type char. It doesn't work:
#include <iostream>
#include <string>
#include <Windows.h>
#include <complex>
using namespace std;
int main()
{
char str[10];
cin >> str;
if(str[10].find_first_of('z')!=string::npos)
{
cout << "nazwa: " << str[10] << endl;
}
return (0);
}
Error: "'find_first_of'must have class\struct\union";
Compiler stressed word "str" in if(**str**[10]...) -> expression must have class type.
find_first_of is a method on string. You can only use it on an object of that type:
std::string str
cin >> str;
if (str.find_first_of('z') != std::string::npos) {
// ....
}
A char array, while serving the same purpose, is not a string, so neither your cin nor your function work. To use an array instead, you'd have to do:
char str[10];
for (int i = 0; i < 10; ++i) {
cin >> str[i];
}
if (std::find(str, str + 10, 'z') != (str + 10)) {
// ....
}
I need to convert a string in C++ to full upper case. I've been searching for a while and found one way to do it:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
transform(input.begin(), input.end(), input.begin(), toupper);
cout << input;
return 0;
}
Unfortunately this did not work and I received this error message:
no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,
I've tried other methods that also did not work. This was the closest to working.
So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.
I got most of my info here:
http://www.cplusplus.com/forum/beginner/75634/
(last two posts)
You need to put a double colon before toupper:
transform(input.begin(), input.end(), input.begin(), ::toupper);
Explanation:
There are two different toupper functions:
toupper in the global namespace (accessed with ::toupper), which comes from C.
toupper in the std namespace (accessed with std::toupper) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast<int (*)(int)>(&std::toupper)
Since you're using namespace std, when writing toupper, 2. hides 1. and is thus chosen, according to name resolution rules.
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Convert a String In C++ To Upper Case
Try this small program, straight from C++ reference
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <cctype>
using namespace std;
int main()
{
string s;
cin >> s;
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
cout << s;
return 0;
}
Live demo
You could do:
string name = "john doe"; //or just get string from user...
for(int i = 0; i < name.size(); i++) {
name.at(i) = toupper(name.at(i));
}
Uppercase to Lowercase and viceversa using BitWise operators
1.
string s = "cAPsLock";
for(char &c: s)
c = c | ' '; // similar to: c = tolower(c);
cout << s << endl; // output: capslock
string s = "cAPsLock";
for(char &c: s)
c = c & ~' '; // similar to: c = toupper(c);
cout << s << endl; // output: CAPSLOCK
PS: for more info check this link
#include <iostream>
using namespace std;
//function for converting string to upper
string stringToUpper(string oString){
for(int i = 0; i < oString.length(); i++){
oString[i] = toupper(oString[i]);
}
return oString;
}
int main()
{
//use the function to convert string. No additional variables needed.
cout << stringToUpper("Hello world!") << endl;
return 0;
}
Like leemes said, you can use toupper(int). Like this:
void ToUpper(string &str) {
for (auto beg = str.begin(); beg != str.end(); ++beg) {
*beg = toupper(*beg);
}
}
It'll through in each character from str and convert it to upper. Example:
int main()
{
string name;
cout << "Insert a name: ";
cin >> name;
ToUpper(name);
cout << "Name in upper case: " << name << endl;
}
You can also use the function from code below to convert it to Upper-case.
#include<iostream>
#include<cstring>
using namespace std;
//Function for Converting Lower-Case to Upper-Case
void fnConvertUpper(char str[], char* des)
{
int i;
char c[1 + 1];
memset(des, 0, sizeof(des)); //memset the variable before using it.
for (i = 0; i <= strlen(str); i++) {
memset(c, 0, sizeof(c));
if (str[i] >= 97 && str[i] <= 122) {
c[0] = str[i] - 32; // here we are storing the converted value into 'c' variable, hence we are memseting it inside the for loop, so before storing a new value we are clearing the old value in 'c'.
} else {
c[0] = str[i];
}
strncat(des, &c[0], 1);
}
}
int main()
{
char str[20]; //Source Variable
char des[20]; //Destination Variable
//memset the variables before using it so as to clear any values which it contains,it can also be a junk value.
memset(str, 0, sizeof(str));
memset(des, 0, sizeof(des));
cout << "Enter the String (Enter First Name) : ";
cin >> str; //getting the value from the user and storing it into Source variable.
fnConvertUpper(str, des); //Now passing the source variable(which has Lower-Case value) along with destination variable, once the function is successfully executed the destination variable will contain the value in Upper-Case
cout << "\nThe String in Uppercase = " << des << "\n"; //now print the destination variable to check the Converted Value.
}