繁体   English   中英

使用getline()输入字符串的问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM