• Advertisement
Sign in to follow this  

variable counter gone wrong.

This topic is 3230 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I wanted to practice using C strings a bit so I started making a variable counter. It is a relatively simple program. The user types in a sentence (up to 500 characters) and the number of total vowels and the number of each individual vowel is shown. Though it is not the most accurate (capital letters are not yet counted) I seem to be having a major problem. The program is giving obscene numbers for the responses. Could someone help me understand what I did wrong. It is probably something simple but I cant seem to find it.
#include <iostream>    //include I/O and string functions
#include <string.h>
using namespace std;

int main()//main function
{
    int vowel; //declare int's a e i o u and vowel
    int a;
    int e;
    int i;
    int o;
    int u;
    char sentence[500]; //declare cstring char with 499 spaces for text
    cout<<"Welcome to the vowel counter please input your sentence.:  ";//prompt user for text
    cin.getline(sentence,499);
    cout<< "\n\n";//spaces
    for(int p=0;p<=strlen(sentence);p++) // search through string sentence.
    {
        if (sentence

== 'a'){ //if mark if charactor a e i o or u are in the sentence and vowel += 1; // add one to vowel a += 1;//add one to a e i o or u variables. } if (sentence

== 'e'){ vowel += 1; e += 1; } if (sentence

== 'i'){ vowel += 1; i += 1; } if (sentence

== 'o'){ vowel += 1; o += 1; } if (sentence

== 'u'){ vowel += 1; u += 1; } } cout<< "there are " << vowel <<" vowels in the sentence\n"; //display data cout<< "there are \n " << a << " a's,\n " << e << " e's\n "<< i << " i's\n " << o << " o's\n " << u << " u's \n "; return 0; }

thanks to anyone who can help me.

Share this post


Link to post
Share on other sites
Advertisement
Initializing your variables would probably help.

Share this post


Link to post
Share on other sites
Hint: Variable values don't default to zero, you must explicitly give them an initial value if you don't want garbage. :)

Also, consider using switch statements and the increment ('++') operators. Less typing, more readable.

EDIT: Ninja'd.

Share this post


Link to post
Share on other sites
and it works. I knew it would be something stupid like that.....it usually is. :) Well thanks for the help. Now I have to build it using the string class.

Share this post


Link to post
Share on other sites
You also might want to consider increasing the warning level of your compiler. For example, MSVC spits out "warning C4700: uninitialized local variable 'a' used" (x5 for each of the vowels) for your code.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement