我需要有關C字符串和函數的分配方面的幫助。顯示字符串的最後n個字符
#include <iostream>
using namespace std;
//other functions
char display_last_nchar(char sent[], int n); // function i'm having trouble with
void main()
{
char sentence[31];
int selection, n;
do {
cout << "Please enter a string: " << endl;
cin.getline(sentence, 31, '\n'); //also, for me here i have to hit enter twice. How can I fix that?
cin.ignore();
cout << "Please make a selection: " << endl;
//other options
cout << "4. Display the last n character of the string " << endl;
cout << "7. Exit" << endl;
cin >> selection;
cin.ignore();
switch (selection)
{
case 4:
cout << "How many characters from the end of the string "
<< "do you want to display? : " << endl;
cin >> n;
cin.ignore();
if (n >= 30)
{
cout << "Error: too many characters" << endl;
break;
}
else
display_last(sentence, n);
cout << sentence << endl;
break;
case 7:
break;
}
}
while (choice != 7);
//other functions
char display_last_nchar(char sent[], int n)
{
for (int i = n; n > 30; i++)
{
sent[i]; //I know this is wrong but this is a guess that i took
}
return sent[n];
}
我知道如何顯示字符串的前n個字符。對於這個功能,如果用戶輸入一個名爲「我的倉鼠有一個新玩具」的字符串,並且他們想要顯示前8個字符,它會在第8個字符後面設置任何字符爲空,因此只顯示「我的火腿」。
我試圖做的是,爲display_last_nchar設置,用戶輸入數字前的每個字符都爲0,但所做的全部字符串都是空的。
難道有人請向我解釋一下,爲了創建一個能顯示字符串最後n個字符的函數,我需要採取的步驟。我試過在網上和我的書上看,但它並沒有真正幫助我。
你想只顯示或顯示和修改原始? – Zeokav
我只想顯示用戶輸入的號碼後的字符。所以如果字符串是「Hello there」,並且用戶想要顯示字符串的最後3個字符,那麼只有「ere」會顯示在main中。 –