I don't have a clue if gets() adds the terminating character (\0) to the array, but getline does so as in:
Your for loop is not check if there is a \0 character in s. Instead, it is iterating until I is less than the ASCII value of \0, which happens to be 0. This means that your for loop shouldn't execute at all. Consider the following code:
1 2 3 4 5
|
int iter=0;
while(s[iter] != '\0' || iter < 100){
C++;
iter++;
}
|
This will iterate through the s array until it reaches a terminating character or the limit of the array.
I would like to point out that you are using more headers than you need (and the wrong ones too). iostream is the standard header for C++ projects. I will explain why you don't need the other two below:
- conio.h is a deprecated header whose functions do not act the same among different compilers. You may not experience this problem as many of the differences are minute (as with getch() ), but for your code to be more flexible, stick with the standard.
- stdio.h is actually a C file. The C++ version is cstdio. This is actually part of the standard,
but mixing I/o methods is generally not a good idea unless you go through the trouble of syncing.
Your code roughly translated to C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char s[100];
int C=0;
cout << "Write something down: ";
cin.getline(s, 99);
for(int I = 0; s[I] != '\0', I < 100; I++)
C++
cout << "Your entry has " << C << " characters!" << endl;
cin.ignore(10000,'\n');
return 0;
}
|
Edit:
FML, I am such a slow typer. :(