gpt4 book ai didi

c++ - 显示字符串的最后 n 个字符

转载 作者:行者123 更新时间:2023-11-28 00:00:13 25 4
gpt4 key购买 nike

我需要有关 C 字符串和函数的作业方面的帮助。

#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 个字符。对于该函数,如果用户输入一个名为“My hamster has a new toy”的字符串并且他们想要显示前 8 个字符,它将把第 8 个字符之后的所有字符设置为空,因此只显示“My hams”。

我尝试做的是,因为设置了 display_last_nchar,用户输入数字之前的每个字符都为 0,但所做的只是将整个字符串设为 null。

有人可以向我解释一下我需要采取哪些步骤来创建一个函数来显示字符串的最后 n 个字符。我试过在网上和我的书中查找,但它并没有真正帮助我。

最佳答案

使用 C++ 字符串 STL。 substr方法在这里很有用。例如,输出字符串的最后 n 个字符

#include <bits/stdc++.h>
using namespace std;

int main() {
string s;
int n;
getline(cin, s);
cin >> n;
if (n < s.length())
cout << s.substr(s.length() - n) << endl;
else
cout << "Not enough characters\n";
return 0;
}

输入

My hamster has a new toy
5

输出

w toy

关于c++ - 显示字符串的最后 n 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39694559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com