0

The code is shown following, the string library has been commented, but the program still work well

#include<iostream>
//#include<string>   // the string library has been commented 
using namespace std;

int main(){
    int n;
    cin>>n;
    for(int i=0; i<n; i++){
        string str;
        int num = 0;
        cin>>str;
        int len = str.length();    //the function length is used here!
        for (int j =0; j< len; j++){
           if (str[j] >='0' && str[j] <='9')
               num ++;
        } 
    cout<<num<<endl;
    }
    return 0;
}
Jie Zhang
  • 39
  • 3
  • How could you use `string` without including the library? – Khalil Khalaf Jul 25 '16 at 14:41
  • [This shows that it doesn't work](http://rextester.com/PHCGB87223). If you want to use `std::string`, then `#include` it. It doesn't matter if by chance your compiler just happens to include internally somewhere in the compiler's set of #includes, you're to assume nothing and always #include the file that prototypes or defines the functions and classes you're using in your code. – PaulMcKenzie Jul 25 '16 at 15:56

1 Answers1

1

Because internally iostream includes string.

Includes are transitive, and some of the dependencies might be compiler dependent, while others will be the same on all platforms (one such example is that including map will make pair available, as it depends on it directly).

The dependency between string and iostream isn't defined anywhere, so while it might work on some compilers, you shouldn't depend on it.

Dutow
  • 5,638
  • 1
  • 30
  • 40
  • And one famous compiler that is probably used by many, if not most programmers is `Visual C++`. The code will refuse to compile with any version of Visual C++, including the latest version. – PaulMcKenzie Jul 25 '16 at 16:00