I wrote a code that counts numbers of words in a sentence, simply by counting spaces... but instead of showing a true number it shows a wrong number.
What's wrong?!
(TurboC++)
You're counting beyond the end of the string. Even though you have a 1000 character buffer, you may have a 20 character string in it. So you need to stop counting when you hit the end of the string.
cin >> ehReads the first word. I knows about white space and uses it white space characters (space, tab, newline) as input delimiters. You need to read with getline.
Input: "Hello word" (without quotes)
then after hitting enter this will be displayed:"0" (without quotes)
Even if you write "Bla Bla Bla Bla Bla " instead of 5 it says 0!
//#include <iostream.h> -> Deprecated header. Instead use <iostream>
//#include <conio.h> -> Not needed
#include <iostream>
// needed to use cout standalone.
using std::cin;
using std::cout;
int check(char eh[10000])
{
int he=0;
for (int i=0; i<10000 ;i++) // remove the '='. eh[10000] is out of bounds.
{
if (eh[i]==' ') he++;
}
return he;
}
int main() // main should return an int.
{
char eh[10000];
for (int i=0; i<10000; i++) // remove the '='. eh[10000] is out of bounds.
{
eh[i]=97;
}
cout<<"Write your words";
cin.getline( eh ); // this reads the entire line. '>>' truncates on white spaces.
cout << check(eh) << "\n";
cin.get();
return 0;
}
1) use #include <iostream>
2) you can initialise the array thus:
char eh[1000] = {0};
... instead of having to loop through the whole array
2) pass a char* to the argument list of your check function
3) use cin.getline instead of cin >> eh, as cin >> will only read up to first space char, and you are intending to include the spaces as you want to count them
Thank you guys, but my TurboC++ doesn't have "IOSTREAM" library and I can't find the library for it, I'll tried the old style (non ANSI/ISO C++ (=IOSTREAM.H) ) and is working, I should have used cin.getline(,) instead of cin, here's what I wrote:
#include <iostream.h>
#include <conio.h>
int check(char* eh)
{
int he=0;
for (int i=0; i<10000 ;i++)
{
if (eh[i]==' ') he++;
}
return he;
}
void main()
{
clrscr();
char eh[10000] = {0};
cout << "Write your words";
cin.getline(eh, 10000);
cout << "\n" << check(eh)+1;
getch();
}
But I still didn't get why we can't use "cin"????? "ajh32" said it only reads up to the first spaces, so why that happens? does anyone know the reason?
First, get a better compiler (Turbo C++ is something like 20 years old), try Code::Blocks or something. The reason is simply how cin operates: It takes in all the characters until the first whitespace, and converts that into the type of the parameter you passed. This is to allow for, say, turning a line into a string, double and struct one after the other, with as much ease as possible. This is why you are required to use getline(), to explicitly collect the entire line and turn it into a string.