Reading a string with istream operator>> will terminate on the first
whitespace, null character of end of line[
^]. The way to read a complete line is to use
std::getline(cin, a[i])
.
This gets the lines correctly, but there is an issue with using
cin >> n
. The input terminates on the first non-digit. The next digit is not consumed. So when you go to read the first line it actually reads the an empty line. The way to correct this is to use
cin.ignore()
, which extracts and ignores characters from the input stream. When used with no parameters
ignore
will read a single character (expecting this to be the enter key).
The final problem with your code is the line reading loop, you need to use
i<n
rather than
<code>
i<n-1 to read in the correct number of lines.
My version of your code is:
#include <iostream>
#include <string>
using namespace std;
int jomleTokalame(string s)
{
string::iterator i;
int sentence;
int count = 0;
for (i = s.begin(); i != s.end(); i++)
{
if(*i != ' ' && *i != '.')
{
count++;
}
}
return count;
}
int main()
{
int n;
string a[50];
string s;
int i=1,j,k=0,g;
cout<<"plz enter the number of lines:"<<endl;
cin>>n;
cin.ignore();
for(int i=0 ; i<n ; i++)
{
getline(cin, a[i]);
g=jomleTokalame(a[i]);
cout<<g<<endl;
}
return 0;
}