我正在嘗試在用戶輸入的位置列印單詞的第一個字母。如果有空格,那么它將停止搜索。有一個關于功能的溫暖資訊gets()。我的指標和功能有問題,它只是不回傳字母。我認為問題可能正在while回圈中。函式firstLetter列印單詞的第一個字母。例如,如果用戶輸入先前輸入的字串的索引 5,并且在 str[5] 中對應于單詞“ice-cream”的“e”,那么firstLetter將搜索該單詞的第一個字母,在這種情況下它會回傳“我”。
#include <stdio.h>
#include <string.h>
int firstLetter(int , char *);
int main()
{
char str[200];
printf("Insert line: ");
gets(str);
int pstn;
scanf("%i,&pstn");
firstLetter(pstn, str);
return 0;
}
int firstLetter(int i, char *str)
{
if(str[i]=' ')
{
printf("No letters at this position");
}
else
{
while(str[i]!=' ')
{
i--;
}
printf("First letter: %c ",str[i 1]);
}
return 0;
}
uj5u.com熱心網友回復:
對于此行的初學者
scanf("%i,&pstn");
你有一個錯字。至少你需要像這樣重寫它
scanf("%i",&pstn);
同樣在函式firstLetter中,if陳述句中也有一個錯字
if(str[i]=' ')
您在哪里使用賦值運算子=而不是比較運算子==。
該函式gets不安全且不受 C 標準支持。
而是使用該功能fgets
fgets( str, sizeof( str ), stdin );
該變數pstn應具有無符號整數型別size_t。否則用戶可以輸入負數。
您還需要檢查輸入的位置是否不大于字串的長度。
例如
size_t pstn = 0;
scanf("%zu", &pstn);
if ( pstn < strlen( str ) ) firstLetter(pstn, str);
函式引數應該有限定符 const 因為傳遞的字串在函式內沒有改變
該函式也有一個錯誤,因為在這個while回圈中
while(str[i]!=' ')
{
i--;
}
沒有檢查是否i小于0。
函式的回傳型別int也是無用的。
該函式可以通過以下方式宣告和定義
void firstLetter( const char *str, size_t i )
{
if ( str[i] == ' ' )
{
printf("No letters at this position");
}
else
{
while( i != 0 && str[i-1] != ' ' )
{
i--;
}
printf("First letter: %c\n", str[i] );
}
}
所以在 main 函式被稱為
size_t pstn = 0;
scanf("%zu", &pstn);
if ( pstn < strlen( str ) ) firstLetter( str, pstn );
或者您可以檢查字串中的指定位置是否小于函式中字串的長度,例如
void firstLetter( const char *str, size_t i )
{
if ( !( i < strlen( str ) ) || str[i] == ' ' )
{
printf("No letters at this position");
}
else
{
while( i != 0 && str[i-1] != ' ' )
{
i--;
}
printf("First letter: %c\n", str[i] );
}
}
在這種情況下,該函式被稱為
size_t pstn = 0;
scanf("%zu", &pstn);
firstLetter( str, pstn );
您可以使用標頭中宣告的標準 C 函式' '與空格字符' '和制表符進行比較,而不是與空格字符進行比較。例如'\t'isblank<ctype.h>
#include <string.h>
#include <ctype.h>
void firstLetter( const char *str, size_t i )
{
if ( !( i < strlen( str ) ) || isblank( ( unsigned char )str[i] ) )
{
printf("No letters at this position");
}
else
{
while( i != 0 && !isblank( ( unsigned char )str[i-1] ) )
{
i--;
}
printf("First letter: %c\n", str[i] );
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455477.html
上一篇:提取exec函式的引數
