Why is c++ treating the space bar as null ('\0')?

1k Views Asked by At

my professor asked us to determine the number of vowels in userString without a call to the library.

I am using '\0' in a for loop to figure out when will the string the user input will come to an end because I don't know the exact size they are going to input for the string. I am a beginner programmer so please don't give me complcated answer! thanks.

I have for(int i = 0; userString[i] != '\0'; i++) but the program is treating the space bar as a null character too so I get a problem in the output, if I have a space in the commend line is treats it as a null and terminates the proram

loop at the pictue of the 2 different outputs for refrence. As you can see in output 1 When i have "MianJalal" I get 9 in the terminal but for output 2 When I have "Mian Jalal" (with a space), it treats the space as null and gives me 4, I am aware that '\0' is space in the special chartacer in c++ but it's also null, how can I tell the program i mean null not space?

this is my code,

#include <iostream>
using namespace std;

int main()
{
    int numOfVowels = 0;
    int length = 0;

    char userString[50]; // The string the user will input
    cout << "Enter a sentence to find out how many vowels are in the sentence" << endl;
    cin >> userString;

    for(int i = 0; userString[i] != '\0'; i++) // '\0' means null in a string in c++; if a user doesn't use a index in a char string
    {                                         // the program will know it's a null in syntax '\0'

    if(userString[i] == 'A' or userString [i] == 'a' or userString[i] == 'i')
    {
        numOfVowels++;
    }
    length++;
    }

    cout << length << endl;

return 0;
}
1

There are 1 best solutions below

1
sergiom On

The problem is that the operator >> uses the space as a delimiter. So when reading userString it stops at the first space. To avoid this a method could be to use istream::getline (char* s, streamsize n ) function, that reads the entire line up to the '\n' character, or the supplied size limit.

#include <iostream>
using namespace std;

int main()
{
    int numOfVowels = 0;
    int length = 0;

    char userString[50]; // The string the user will input
    cout << "Enter a sentence to find out how many vowels are in the sentence" << endl;
    cin.getline(userString, sizeof(userString));

    for(int i = 0; userString[i] != '\0'; i++) // '\0' means null in a string in c++; if a user doesn't use a index in a char string
    {                                         // the program will know it's a null in syntax '\0'

        if(userString[i] == 'A' or userString [i] == 'a' or userString[i] == 'i')
        {
            numOfVowels++;
        }
        length++;
    }

    cout << length << endl;

    return 0;
}