#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;
}
getline怎么用啊,cin输入带空格的字符串怎么办,我的程序拿错了
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 猫叔大鸭梨 2021-03-15 01:03关注
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:- An explicit extraneous initial call to
getline
- Removing consecutive whitespace with std::cin >> std::ws
- Ignoring all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
简单来说,你用cin >> repeat获得数值的时候会留下一个换行符在输入流,getline的时候就把一行给读了,里面肯定是空的,这样就会有问题了。
在没有cin之前直接用getline是没问题的。
如果帮到你了,麻烦点个采纳呗。^_^
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 - An explicit extraneous initial call to
悬赏问题
- ¥15 微信公众号自制会员卡没有收款渠道啊
- ¥15 stable diffusion
- ¥100 Jenkins自动化部署—悬赏100元
- ¥15 关于#python#的问题:求帮写python代码
- ¥20 MATLAB画图图形出现上下震荡的线条
- ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
- ¥15 perl MISA分析p3_in脚本出错
- ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
- ¥15 ubuntu虚拟机打包apk错误
- ¥199 rust编程架构设计的方案 有偿