Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my program give "NULL used in arithmetic" [closed]

Tags:

c++

string

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?

like image 719
user3723273 Avatar asked Jun 09 '14 17:06

user3723273


People also ask

What is null in programming languages?

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.

When to use null as an argument to an object?

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.)

What is the use of null pointer in if statement?

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.

Can null be used to denote an error condition?

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?


2 Answers

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";
like image 44
haccks Avatar answered Nov 10 '22 10:11

haccks


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')
like image 192
R Sahu Avatar answered Nov 10 '22 09:11

R Sahu