Dilshad
Dilshad

Reputation: 1

cout is only working after gets() eventhough i had written it before gets()

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

Upvotes: 0

Views: 44

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596652

The problem is that std::cout is buffered, and you are not flushing the buffer to the console before calling gets(), which has no concept of std::cout or its buffer. So, you will have to flush the buffer manually, either by writing a '\n' character to the output, eg:

cout << "Type a sentence\n";
gets(str);

Or, using the std::endl or std::flush manipulator:

cout << "Type a sentence" << endl; // writes '\n' and then flushes
gets(str);
cout << "Type a sentence" << flush; // just flushes without writing '\n' first
gets(str);

Or, calling the std::cout.flush() method directly, eg:

cout << "Type a sentence";
cout.flush();
gets(str);

But, you really should not be mixing C-style I/O and C++-stye I/O. std::cin and std::cout are tie()'d together by default, so if you had used std::cin instead of gets() to read the input, then std::cin would have first flushed std::cout's buffer automatically.

Try this instead:

#include <iostream>
using namespace std;

int main() {
   char str[50] = {};
   int vow = 0;
   cout << "Type a sentence: ";
   cin.getline(str, 50);
   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;
}

Or, using std::string instead of char[]:

#include <iostream>
#include <string>
using namespace std;

int main() {
   string str;
   int vow = 0;
   cout << "Type a sentence: ";
   getline(cin, str);
   for(size_t i = 0; i < str.size(); ++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;
}

Upvotes: 2

Related Questions