我需要撰寫一個程式,用戶輸入字串的數量,程式計算每個字串中元音的數量并列印元音的總數。以下代碼在沒有二維陣列的情況下作業
int countVoweles(char inputArray[])
{
int total = 0;
char vowels[] = "aAeEiIoOuU";
for (int i = 0; inputArray[i]; i )
{
for (int j = 0; vowels[j]; j )
{
if (inputArray[i] == vowels[j])
{
total ;
}
}
}
return total;
}
但是,以下代碼不適用于二維陣列。它僅從第一個字串列印元音。
如何從輸入的所有字串中列印元音?
char name[3][10];
int total = 0;
char vowels[] = "aAeEiIoOuU";
printf("Enter your string :");
for (int i = 0; i < 3; i )
{
gets(name[i]);
}
printf("The total number of vowels are :\n");
for (int i = 0; i < 3; i )
{
for (int j = 0; name[i][j]; j )
{
if (name[i][j] == vowels[i])
{
total ;
}
}
}
printf("%d", total);
uj5u.com熱心網友回復:
對于初學者,請注意該功能gets是不安全的,并且不受 C 標準支持。而是使用標準功能fgets,例如
fgets( name[i], sizeof( name[i] ), stdin );
至于您的問題,那么您還需要一個回圈來遍歷陣列,其中包含vowels陣列字串中的給定字符name。
例如
for (int i = 0; i < 3; i )
{
for (int j = 0; name[i][j]; j )
{
int k = 0;
while ( vowels[k] && name[i][j] != vowels[k] ) k;
if ( vowels[k] )
{
total ;
}
}
}
另一種方法是使用您已經撰寫的函式,例如
for (int i = 0; i < 3; i )
{
total = countVoweles( name[i] );
}
例如,vowels您可以使用strchr在標頭中宣告的標準 C 函式,而不是使用回圈遍歷陣列<string.h>
for (int i = 0; i < 3; i )
{
for (int j = 0; name[i][j]; j )
{
total = strchr( vowels, name[i][j] ) != NULL;
}
}
uj5u.com熱心網友回復:
您的函式需要知道 2D 字符陣列的大小。
size_t countVoweles(size_t lines, size_t chars, char inputArray[lines][chars])
{
size_t total = 0;
const char vowels[] = "aAeEiIoOuU";
for (size_t i = 0; i < lines; i )
{
for (size_t j = 0; inputArray[i][j]; j )
{
total = !!strchr(vowels, inputArray[i][j]);
}
}
return total;
}
int main(void)
{
char x[][256] = {
"<Compilation failed>",
"# For more information see the output window",
"# To open the output window, click or drag the \"Output\" icon at the bottom of this window",
};
printf("%zu\n", countVoweles(sizeof(x)/ sizeof(x[0]), sizeof(x[0]), x));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477692.html
上一篇:如何在C中重復讀取和連接字串
