#include <iostream>
#include <string>
using namespace std;
void strmcpy(string s,int m,string t)
{
int z;
z=t.length();
if(z<=m) cout<<"error input"<<endl;
else
{
string p(t,m);
s=p;
cout<<s<<endl;
}
}
int main()
{
int repeat,m,i;
string t;
string s;
cin>>repeat;
for(i=0;i<repeat;i++)
{
getline(cin,t);
cin>>m;
strmcpy(s,m,t);
}
return 0;
}
cin是不能输入类似 "test ss"这种有空格的,在读取到空格时就停止了。
如果先用了cin,那么要多加2行代码
string str = "\n";
getline(cin, str);
或者是
std::cin >> std::ws;
void strmcpy(string s, int m, string t)
{
int z;
z = t.length();
if (z <= m) cout << "error input" << endl;
else
{
string p(t, m);
s = p;
cout << s << endl;
}
}
int main()
{
int repeat, m, i;
string t;
string s;
cin >> repeat;
for (i = 0; i < repeat; i++)
{
string str = "\n";//多加的代码
getline(cin, str);//多加的代码
getline(cin, t);
cin >> m;
strmcpy(s, m, t);
}
system("pause");
return 0;
}
原因是
When consuming whitespace-delimited input (e.g. int n; std::cin >> n;) any whitespace that follows, including a newline character, will be left on the input stream. Then when switching to line-oriented input, the first line retrieved with getline
will be just that whitespace. In the likely case that this is unwanted behaviour, possible solutions include:
getline
简单来说,你用cin >> repeat获得数值的时候会留下一个换行符在输入流,getline的时候就把一行给读了,里面肯定是空的,这样就会有问题了。
在没有cin之前直接用getline是没问题的。
如果帮到你了,麻烦点个采纳呗。^_^