简体   繁体   中英

Problems with string input using getline()

Here is my solution to the problem in the codeforces http://codeforces.com/problemset/problem/499/B . I am facing problem in inputting the string. It termintes after line 10 (see code) before i give input str to it and output some weird chars.

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;
}

There is a newline character left in the input stream after:

cin>>N>>M;

You need a line of code that will read and discard the rest of the line. Add a line;

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

after that line.

Add

#include <limits>

to be able to use std::numeric_limits .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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