题目如下:
问题 G: 截取字符串(函数)
时间限制: 1 Sec 内存限制: 128 MB
题目描述
编写一个函数int substr(char str1[],char str2[],int index),其作用是,将从字符串str1 (长度超过30) 的第index个字符开始的所有字符复制,生成新的字符串str2,如果成功生成,函数返回1,如果不能成功生成,返回0
输入
测试数据的组数n
第一组数据
第二组数据
........
输出
成功生成就输出子串,不成功生成,输出"IndexError"
样例输入
3
Zhenshen University
9
www.szu.edu.cn
12
apple
8
样例输出
University
cn
IndexError
代码如下:
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
int main() {
int t;
//t = cin.get();
//一开始使用t=cin.get()一直报错,单步调试之后
//发现会导致下面对一行包含字符串的输入
//即getline(cin,ss)直接在ss中输入了一个空字符串
scanf("%d\n", &t);//这里将换行符一并包括进来了
while (t--)
{
string ss;
getline(cin,ss);
int index;
cin >> index;
if (index<0&&index>=ss.length())
{
cout << "IndexError" << endl;
}
else
{
for (int i = index; i < ss.length(); i++)
{
cout << ss[i];
}
cout << endl;
}
}
return 0;
}