C++

I read this code but I don't understand the const chat ent = '\n'; and while (ch! =ent)
1
2
3
4
5
6
7
8
9
10
11
12
13
int chcount=0;
Const chat ent='\n';
Char ch; 
Cout<<"enter character\n";
Cin.get(ch);
While(ch! =ent)
{
Chcount++;
Cout.put(ch);
Cin.get(ch);
}
Cout <<"\nthe number of characters=" <<"\n";
}
'\n' is the newline character. When the user presses the enter key, it sends a newline character '\n' to cin.

 
    const char ent = '\n';
defines a constant named ent which stores a single character and gives it the value '\n'. I guess 'ent' is short for 'enter key' here.

 
while (ch != ent)
This is the start of a loop. It tells the program to repeat the loop while the condition is true. In this case it means repeat until the character ch entered by the user is the newline character ent.
Hello Shubhamkapoor,

I think line 2 was just a typo from someone. The code below is how the program should be written. Line 1 is the only line that was written correctly. It is best to compile the program before posting to see what errors you get and what you can fix before posting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int chCount = 0;
const char ent = '\n';
char ch{ ' ' };

cout << "enter character\n";

cin.get(ch);

while(ch != ent)
{
	chCount++;
	cout.put(ch);
	cin.get(ch);
}

cout << "\nthe number of characters= " << chCount << "\n";
}


Key words like "int", "char", "cin" and "cout" are key words in C and C++. Most of these key words are spelled with lowercase letters. There may be some exceptions that I can not think of right now. Notice how I changed "chcount". This is considered the more proper and more used way of writing a variable name.

For the while condition. This is checking the character entered from the keyboard against "ent". If they do not equal then the condition is true and the while loop executes. When they are equal the condition fails and the while loop is passed by.

Lastly notice the use of blank lines and spaces I used to make the program esier to read. C and C++ compilers do not care about spaces, so use all you need to make the program easier to read. Notice what I did with line 3. You should always initialize your variables.

Hope that helps,

Andy

Topic archived. No new replies allowed.