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

标签 c++

我需要有关 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/

相关文章:

c++ - 您无权写入文件 “ostream” 所在的文件夹

c++ - 如何通过在 Arduino 中引用我的类来传递串行对象?

c++ - 读取二进制数据列

c++ - 可变参数模板且没有值

c++ - 有没有一种方法可以防止单词在C++输出中获得 'cut'?

c++ - unordered_set 与 vector 的迭代速度

c++ - 文件/ifstream 的双向迭代器

C++ rbegin 修改reverse_iterator的地址

c++ - 前向声明的类型和 "non-class type as already been declared as a class type"

c++ - 如何计算 Eigen VectorXi 中交集和并集的元素数量?