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)) {
// ....
}
Related
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
cin.ignore();
while(t--){
string s;
getline(cin,s);
int i =0;
int count =0;
while(i<s.size()){
if(s[i]!=' '){
//cout<<count<<":";
s[count++]=s[i];
}
i++;
}
s[count]='\0';
cout<<s<<endl;
}
return 0;
}
Why in the end String is not terminating with '\0'?
For Input:
2
geeks for geeks
g f g
your output is:
geeksforgeeksks
gfgg f g
To remove a character from a string, you should use erase.
See the remove-erase idiom.
std::string is not a C-style null terminated string (but you can obtain one from it). As such, inserting a null character will not terminate it. If you want to truncate a string from the end, you can simply resize() it. Otherwise, if you want to remove characters, you can erase() them.
You say you want to remove spaces. To do that with your existing code, simply replace s[count]='\0'; with s.resize(count);, eg:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
cin.ignore();
while (t--){
string s;
getline(cin, s);
int i = 0;
int count = 0;
while (i < s.size()){
if (s[i] != ' '){
//cout<<count<<":";
s[count++] = s[i];
}
i++;
}
s.resize(count);
cout << s << endl;
}
return 0;
}
However, a better way to handle this would look more like this:
#include <iostream>
#include <string>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::size_type idx = 0;
while ((idx = s.find(‘ ‘, idx)) != std::string::npos){
s.erase(idx, 1);
}
std::cout << s << std::endl;
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::iterator iter = std::remove(s.begin(), s.end(), ‘ ‘);
s.erase(iter, s.end());
std::cout << s << 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;
}
I wrote this code to detect if an input string has a space or not. Please tell what is wrong in this approach.
#include <iostream>
#include <string>
using namespace std;
int main(){
string inp;
getline(cin, inp);
for (int i = 0; i < inp.length(); i++) {
string z = to_string(inp[i]);
if (z == " ") {
cout << "space";
}
else {
i++;
}
}
}
If i enter a string with spaces, it doesn't print "space".
Since inp is an std::string, inp[i] will be a char. Since std::to_string only has overloads for arithmetic, non-char values, calling it on a char is akin to calling it on the integer representation of said char. (If you log z, you'll likely find a number printed.)
Instead, directly compare inp[i] to a space. else { i++; } is also unnecessary – you may be jumping over spaces.
for (int i = 0; i < inp.length(); i++) {
if (inp[i] == ' ') { // note single quotes for char
cout << "space";
}
}
#TrebledJ's answer explains why your code is broken and how to fix it.
Another way to handle this situation is to use std::string::find() instead:
#include <iostream>
#include <string>
int main(){
std::string inp;
std::getline(std::cin, inp);
if (inp.find(' ') != std::string::npos) {
std::cout << "space";
}
}
Alternatively, your original code tries to output "space" for each space character found. You could use find() in a loop:
#include <iostream>
#include <string>
int main(){
std::string inp;
std::getline(std::cin, inp);
std::string::size_type idx = inp.find(' ');
while (idx != std::string::npos) {
std::cout << "space at " << idx << std::endl;
idx = inp.find(' ', idx+1);
}
}
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.
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.
}