I used cin.get() for two programmes and both of don't work.
1)
int main (int argc, char * const argv[]) {
std::cout << "Enter a string for analysis: " << std::endl;
beta = std::cin.get();
while (beta!=EOF){
character++;
beta = std::cin.get();
}
std::cout << character;
2) int main (int argc, char * const argv[]) {
std::cout << "Enter a string for analysis: " << std::endl;
while (std::cin.get(beta))
character++;
std::cout << character;
when I press an enter key, it go on to the second line instead of going on to display character. Why?
Thx
1. There is NO reason why you would need to treat a character return function like your taking an entire text file as input.
2. How are you defining these variables exactly?
1. Should initialize count = 0;
2. EOF in used to judge if file pointer point to the end of the file. I tested its value in linux: -1.
3. Each input can get though cin.get(ch), that included '\n', space, you can proved by the value of count.
The reason is that cin.get() returns an int, not a char, and assigning an int value to a char variable is not a safe operation. In particular, the test for equality is not safe, because EOF is also an int, and its value does not fit into a char! Usually, EOF==(int)-1.
mingo, wtf? A char is an unsigned 8-bit integer. Assigning a character an integer that is valid as an 8-bit unsigned integer (0 - 255) is fine.
1) In order to get more respected and useful responses, you need to learn how to properly post your questions. And ffs, USE CODE TAGS. I've posted it over 100 times this post....
2) I don't know what book your reading but stop reading it. It apparently doesn't know how to teach and gives bad examples.
3)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int main (int argc, char * const argv[])
{
char ch;
int count = 0;
std::cout << "Enter ur damn input: ";
std::cin.get(ch); //takes a character from input.
while (ch != '#')
{
count++;
std::cin.get(ch);
}
std::cout << std::endl << count << " characters read.";
return 0;
}
This is a slightly modified version of your program that is formatted and fixed. The big problem that you made is that you assumed that count is already 0 when defined.
When you declare a variable: int wtf; It equals whatever was occupying the memory at that time it was allocated (don't quote me... I think it's OS based. For a more clear answer, I suggest a good google). SOOO, it might equal 34234234, 2334234, 341234234, etc. The only way to stop this is to initialize or assign the variable a value that you know such as 0 like I did above. It's good habit to initialize ALL of your variables to something that you can work with.
Never mind, I'm sorry. while(cin.get(ch)) is not valid since it will always return a value higher than 0 which would result in that being an infinite loop. Should have seen that earlier.