#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 HLs设计手写数字识别程序编译通不过
- ¥15 Stata外部命令安装问题求帮助!
- ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
- ¥15 TYPCE母转母,插入认方向
- ¥15 如何用python向钉钉机器人发送可以放大的图片?
- ¥15 matlab(相关搜索:紧聚焦)
- ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
- ¥15 Arduino无法同时连接多个hx711模块,如何解决?
- ¥50 需求一个up主付费课程
- ¥20 模型在y分布之外的数据上预测能力不好如何解决