I wrote the following;
string words;
int a=0;
getline(cin,words);
while(words[a]!=NULL)
{
a++;
}
cout<<a<<endl;
It worked correctly, but when I added the line at the end:
string words;
int a=0;
getline(cin,words);
while(words[a]!=NULL)
{
a++;
}
cout<<a<<endl;
if(words[1]=="a") {cout<<"the letter is a";}
It no longer works. Why?
null is a fundamental concept in many programming languages. It is ubiquitous in all kinds of source code written in these languages. So it is essential to fully grasp the idea of null . We have to understand its semantics and implementation, and we need to know how to use null in our source code.
The basic rule is simple: null should only be allowed when it makes sense for an object reference to have 'no value associated with it'. (Note: an object reference can be a variable, constant, property (class field), input/output argument, and so on.)
NULL is used not as a pointer but as 0. It works since word[a] evaluates to a char and you can compare a char with 0. it fails because you are trying to compare char with "a", whose type is char const*. You probably meant to use: Replace the double quote "" by single quote '' in if conditional expression.
It is important to note that null should not be used to denote error conditions. Consider a function that reads configuration data from a file. If the file doesn’t exist or is empty, then a default configuration should be returned. Here is the function’s signature: What should happen in case of a file read error?
Replace the double quote ""
by single quote ''
in if
conditional expression. Note that NULL
macro is used for null pointer constant not for null constant \0
.
while(words[a]! = '\0')
{
cout<<a<<endl;
a++;
}
if(words[1] == 'a')
cout<<"the letter is a";
In the line
while(words[a]!=NULL)
NULL
is used not as a pointer but as 0
.
It works since word[a]
evaluates to a char
and you can compare a char
with 0
.
In the line
if(words[1]=="a")
it fails because you are trying to compare char
with "a"
, whose type is char const*
.
You probably meant to use:
if(words[1]=='a')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With