Loop is ending too early

Argh... I feel brainwashed...braainss..

The problem is in the first loop of a program, if iIle=2 then it takes string only once (should take twice) and so on.. what`s wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string      sTab[150];
    int         iTab[123];
    int         iIle,iTemp;
    char        cA='A';
    char        ca='a';


    cin>>iIle;
    for (int i=0;i<iIle;i++)
            getline(cin,sTab[i]);
    for (int i=0;i<iIle;i++){
        iTemp=sTab[i].length();
        for(int j=0;j<iTemp;i++)
                iTab[sTab[i][j]]++;
    }
    for (int i=97;i<123;i++){
        if(iTab[i]!=0)
            cout<<ca<<' '<<iTab[i]<<endl;
        ca++;
    }
    for (int i=65;i<91;i++){
        if(iTab[i]!=0)
            cout<<cA<<' '<<iTab[i]<<endl;
        cA++;
    }
}


also, I wanted to ask, are there cases of program not compiling or working wrongly in one compiler, and without problems on other? (not including the cases where someone is trying to use the functions from other compiler and so on)
Problem is that you're using both cin>> and getline(). Always use getline(), never mix it up with cin>> (cin>>integer is a bad idea anyway: if the user inputs something else the program will crash). See for getline(): http://www.cplusplus.com/forum/articles/6046/.

And yes, some code will compile on one compiler and won't on the other. For example, some compilers support void main(), while other compilers only support int main(). You should always try to write code that keeps to the 'standard' rules; that code will compile on all compilers.
When you hit enter for the input at line 16 (giving the number of strings to enter, the stream gets a newline character ( '\n' ) so getline (which reads until it finds a '\n' ) gets on the 1st time the loop is executed an empty string.
To remove that extra '\n' you can call cin.sync() before executing the loop
Thank you all very much :] I used the cin.sync solution, as this task has no chance of getting bad data.

well then, I think I simply should stay with gcc based IDE :]
I would avoid using cin>> in the first place and replace it with getline(). For strings, getline is really easy to use. For numbers getline() is a little more work, but on the other hand, cin>>integer (or cin>>double/cin>>float) gives serious problems when the user inputs something that is not expected and requires you do handle exceptions etc.

[edit]
(Didn't read your post before posting) If there's no chance for bad data, cin.sync() is fine of course. But generally, I would recommend to always use getline().
Last edited on
Topic archived. No new replies allowed.