为什么输入第二个及以后的测试数据都显示error input;
时间: 2024-03-23 11:43:55 浏览: 12
在使用 `getline` 函数读入字符串时,它会读取一行输入,包括输入行末的换行符。而在读取整数 `m` 时,我们使用了 `cin`,它会读取输入行末的换行符之前的内容,并将换行符留在输入流中。因此,在读取第二个及以后的测试数据时,程序会先读取输入流中的换行符,而不是读取整数 `m`,导致输入错误。
为了解决这个问题,我们可以在读取整数 `m` 之前使用 `cin.get()` 读取输入流中的换行符,以便后续读取整数 `m`。修改后的程序如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void strmcpy(char* s, char* t, int m);
int main() {
int repeat;
cin >> repeat;
cin.get();
for (int i = 0; i < repeat; i++) {
char t[100], s[100];
int m;
cin.getline(t, 100);
cin.get(); // 读取输入流中的换行符
cin >> m;
s[0] = '\0'; // 初始化字符串 s
strmcpy(s, t, m);
cout << s << endl;
}
return 0;
}
void strmcpy(char* s, char* t, int m) {
int len = strlen(t);
if (m > len || m < 1) {
cout << "error input" << endl;
} else {
for (int i = m - 1; i < len; i++) {
s[i - m + 1] = t[i];
}
s[len - m + 1] = '\0'; // 在字符串末尾添加结束符
}
}
```
在上述程序中,我们在读取整数 `m` 前使用了 `cin.get()` 读取了输入流中的换行符,以确保后续读取整数 `m` 时不会受到影响。这样,即可正确地处理多组测试数据。