C ++ getline方法不工作 [英] C++ getline method not working

查看:363
本文介绍了C ++ getline方法不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,但我是C ++的新手,但不是一般的编程。所以我试图做一个简单的加密/解密。然而,当我添加修改到我以前的代码(所以没有两个程序加密和解密)我发现代码'getline()'方法不再工作。相反,它只是在代码运行时忽略它。这里是代码:

I'm sorry but I'm quite new to C++ but not programming in general. So I tried to make a simple encryption/decryption. However when I added the modification to my previous code (so there isn't two programs for encrypting and decrypting) I found that the code 'getline()' method no longer works. Instead it's just ignoring it when the code is ran. Here's the code:

int main(){
    std::string string;
    int op = 1; //Either Positive or Negative

    srand(256);
    std::cout << "Enter the operation: " << std::endl;
    std::cin >> op;
    std::cout << "Enter the string: " << std::endl;
    std::getline(std::cin, string); //This is the like that's ignored

    for(int i=0; i < string.length(); i++){
        string[i] += rand()*op; //If Positive will encrypt if negative then decrypt
    }
    std::cout << string << std::endl;

    std::getchar(); //A Pause 
    return 0;
}


推荐答案

c> std :: cin>> op; 在你的代码中留下一个悬挂 \\\
,这是第一件事 getline 读取。由于 getline 在找到换行符字符时停止读取,函数立即返回,不再读取任何内容。您需要忽略此字符,例如,使用 cin.ignore(std :: numeric_limits< std :: streamsize> :: max(),'\\\
');
std :: numeric_limits 在标题< limits> 中定义),如 cppreference

That's because std::cin >> op; leaves a hanging \n in your code, and that's the first thing getline reads. Since getline stops reading as soon as it finds a newline character, the function returns immediately and doesn't read anything more. You need to ignore this character, for example, by using cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); (std::numeric_limits is defined in header <limits>), as stated on cppreference.

这篇关于C ++ getline方法不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆