#include <iostream>
using namespace std;
int main(){
int a=4,b=8;
float r=5.55;
char c='comica';
cout<<"this is a test and value of surtd is"<<a<<".\n and value of sturd is"<<b;
cout<<"value of me is"<<'c';
return 0;
}
I did all things as shown in a lecture, but it is showing an error in the compiler.
Use the correct return 0 not return=0 and also char should hold one char not string
Code should be
#include <iostream>
using namespace std;
int main(){
int a=4,b=8;
float r=5.55;
char c='c';
cout<<"this is a test and value of surtd is"<<a<<".\n and value of sturd is"<<b;
cout<<"value of me is"<<c;
return 0;
}
char is used for storing single charecter. for storing a sequence of characters use std::string class.
string c = "comica";
//Note: Use double quotes for strings. single quotes are for charecter
Remove the quotes around variable c, Otherwise it'll print charecter c and not the value of string object c.
cout<<"value of me is"<<c;
as said in comments use return 0. return=0 is invalid.
There are multiple mistakes in your code:
Using a char variable initialized with a multi-byte character literal.
Initializing a float variable with a double literal (and then not even using the variable afterwards).
Passing a 'c' character literal to operator<< instead of your c variable.
Using a misplaced - in the return statement.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main(){
int a = 4, b = 8;
//float r = 5.55f;
string s = "comica";
cout << "this is a test and value of surtd is " << a << ".\n and value of sturd is " << b;
cout << ".\n and value of me is " << s;
return 0;
}
Related
I am trying to reverse the digits of a number. I used strings in it. And I am bound to use strings. Program just give last digit and stop executing. For instance if I put 123 as an input and I only get 3. Instead I should be having 321.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b=0;
cin>>a;
string str1="", str="";
for(int i=0;a>0;i++)
{
b=a%10;
str=to_string(b);
a=a/10;
str1=str1+str;
}
cout<<str1.length();
}
Simply change this cout<<str1.length(); to cout<<str1;.
However it's better to use while loop instead of weird for loop.
int main()
{
int a,b=0;
cin>>a;
string str1="", str="";
cout << a << "\n";
while (a>0)
{
b=a%10;
str=to_string(b);
a=a/10;
str1=str1+str;
}
cout<<str1;
}
You're printing the string length rather than string itself.
You are Printing length of string .length() is a builtin function provided by strings. Try running it again by removing .length() keyword from cout command i.e. cout << str1
I'm trying to split a string into an array of individual characters. However, I would like the string to be input by the user, for which I need to define the string using a variable.
My question is, why does this work:
#include <iostream>
using namespace std;
int main() {
char arr [] = {"Giraffe"};
cout << arr[0];
return 0;
}
But this doesn't?
#include <iostream>
using namespace std;
int main() {
string word;
word = "Giraffe";
char arr [] = {word};
cout << arr[0];
return 0;
}
Thanks
Your example doesn't work because you're trying to put a std::string into an array of char. The compiler will complain here because std::string has no type conversion to char.
Since you're just trying to print the first character of the string, just use the array accessor overload of std::string, std::string::operator[] instead:
std::string word;
word = "Giraffe";
std::cout << word[0] << std::endl;
In your second example, the type of word is a std::string and there are no default type conversions from std::string to the type char.
On the other hand, the first example works because it can be interpreted as an array of char (but actually its just c-style const char *).
If, for some reason, you would want to convert std::string into the c-style char array, you might want to try something like this...
#include <iostream>
#include <string>
#include <cstring>
int main(void)
{
std::string word;
word = "Giraffe";
char* arr = new char[word.length() + 1]; // accounting for the null-terminating character
strcpy(arr, word.data());
std::cout << arr[0] << std::endl;
delete[] arr; // deallocating our heap memory
return 0;
}
Input : <div5 id="abc" style="....">xyz</div5>
I want to assign this to a string variable but because of quote ,this cannot be directly assigned to a string variable .
How can I take this input .
So that I can assign to a string variable
You'll need to escape the quotes:
#include <iostream>
std::string x = "<div5 id=\"abc\" style=\"....\">xyz</div5>";
The same goes for Java:
String x = "<div5 id=\"abc\" style=\"....\">xyz</div5>;
To get it from the user in C++:
#include <iostream>
std::string x;
std::getline(std::cin, x);
And in Java:
String x = new Scanner(System.in).nextLine();
#include<iostream>
#include<strirng>
using namespace std;
int main()
{ string a,b;
getline(cin,a,'\"');//input end when there is a "
getline(cin,b,'\"');//because " is a wide space character,need to put\
before it
cout<<a<<" "<<b<<endl;
return 0;
}
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
reverse(begin(s), end(s));
cout << s << endl;
return 0;
}
prints olleh
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s[5] = {"hello"};
reverse(begin(s), end(s));
cout << *s << endl;
return 0;
}
prints hello
Please help me understand why is such difference. I am newbie in c++, I am using c++ 11.
Ok, I corrected to s[5]={"hello"} from s[5]="hello" .
The first is a single string. The second is an array of five strings, and initializes all five string to the same value. However, allowing the syntax in the question is a bug (see the link in the comment by T.C.) and should normally give an error. The correct syntax would have the string inside braces, e.g. { "hello" }.
In the second program you are only printing one string of the five anyway, the first one. When you dereference an array, it decays to a pointer and gives you the value that pointer points to, which is the first element in the array. *s and s[0] are equivalent.
I think that what you are looking for is this:
int main() {
char s[] = "hello";
reverse(s, s + (sizeof(s) - 1));
cout << string(s) << endl;
return 0;
}
With char[6] you have an C-style string. Remember that theses strings must be terminated with '\0'. Therefore there is a 6th element.
Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char.
I used the code(snippet)
string word;
openfile >> word;
double lol=word;
I receive the error that
Code1.cpp cannot convert `std::string' to `double' in initialization
What does the error mean exactly? The first word is the number 50. Thanks :)
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999 (which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
If you are reading from a file then you should hear the advice given and just put it into a double.
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
Here is a (very simple) example:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
Compile and run this program, then study it. It is simple
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
Coversion from string to double can be achieved by
using the 'strtod()' function from the library 'stdlib.h'
#include <iostream>
#include <stdlib.h>
int main ()
{
std::string data="20.9";
double value = strtod(data.c_str(), NULL);
std::cout<<value<<'\n';
return 0;
}
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}