简体   繁体   English

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

[英]Problems with string input using getline()

Here is my solution to the problem in the codeforces http://codeforces.com/problemset/problem/499/B . 这是我在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. 它在第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;
}

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 . 才能使用std::numeric_limits

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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