[英]Problems with string input using getline()
這是我在codeforces中的問題解決方案http://codeforces.com/problemset/problem/499/B 。 我在輸入字符串時遇到問題。 它在第10行之后終止(請參閱代碼),然后再給我輸入str並輸出一些奇怪的字符。
Input: 4 3
codeforces codesecrof
contest round
letter message
Output:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
int N, M;
string str;
cin>>N>>M;
string A[M], B[M];
for(int i=0; i<M; i++)
cin>>A[i]>>B[i]; // line 10
getline(cin,str);
char res[N+1];
for(int i=0; i<M; i++){
int j= str.find(A[i]);
int k;
int x=0;
if(B[i].length() < A[i].length()){
for(k=j; k<B[i].length(); k++){
res[k]= B[i][x];
x++;
}
}else{
for(k=j; k<B[i].length(); k++){
res[k]= B[i][x];
x++;
}
}
res[k]=' ';
}
for(int i=0; i<=N; i++ )
cout<<res[i];
cout<<endl;
return 0;
}
在以下位置,輸入流中還有一個換行符:
cin>>N>>M;
您需要一行代碼來讀取並丟棄其余的代碼。 添加一行;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
在那條線之后。
加
#include <limits>
才能使用std::numeric_limits
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.