I have just started learning c++.
I wrote this program for finding how many vowels in a sentence.
But when i run the program it asking for input before the cout and cout is working after gets()
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
char str[50];
int vow;
cout<<"Type a sentence";
gets(str);
for(int i=0; str[i]!='\0';i++){
switch(str[i]){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vow++;
}
}
cout<<"There are "<<vow<<" vowels in the string "<<str;
return 0;
}
output
hello world
Type a sentenceThere are 3 vowels in the string hello world
The problem is that
std::coutis buffered, and you are not flushing the buffer to the console before callinggets(), which has no concept ofstd::coutor its buffer. So, you will have to flush the buffer manually, either by writing a'\n'character to the output, eg:Or, using the
std::endlorstd::flushmanipulator:Or, calling the
std::cout.flush()method directly, eg:But, you really should not be mixing C-style I/O and C++-stye I/O.
std::cinandstd::coutaretie()'d together by default, so if you had usedstd::cininstead ofgets()to read the input, thenstd::cinwould have first flushedstd::cout's buffer automatically.Try this instead:
Or, using
std::stringinstead ofchar[]: