簡體   English   中英

C ++ getline cin錯誤

[英]c++ getline cin error

#include <iostream>
#include <string>
using namespace std;
int main(){
    int a1,a2,a3,a4;

cin>>a1>>a2>>a3>>a4;
string a;
getline(cin,a);
return 0;}

我有這個代碼。 我無法輸入“ a”的值。 請幫幫我

您可以使用std::ws從輸入流中丟棄前導空格。

#include <iostream>
#include <string>

int main()
{
  int a1, a2, a3, a4;
  std::cin >> a1 >> a2 >> a3 >> a4;

  std::string a;
  std::getline(std::cin >> std::ws, a);

  return 0;
}

cin實際上將整數和一個'\\n'在輸入緩沖區中。

因此,當流到達getline語句時,它只會得到一個'\\n'


無論如何,直接讀取數字是有問題的:當cin被提供輸入時,它無法處理,它將進入失敗狀態。

它無法處理的輸入將留在輸入流中,並被忽略,直到清除“失敗”狀態( std::cin.clear()std::cin.clear()

因此,您應該檢查輸入流是否無效( !std::cin ):

std::cin >> a1;
if (!std::cin)
{    
  std::cin.clear();
  std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');

  // Get the input again / handle the error
}

諸如cppreference.com類的良好文檔非常清楚地說明了問題:

在用空格分隔的輸入后立即使用時,例如int n; std::cin >> n; int n; std::cin >> n; getline使用operator>>消耗輸入流上剩余的結束operator>> ,並立即返回。

不過,我想提出一種替代解決方案,而不是忽略剩余字符。 通常,您應該考慮一種編程風格,其中所有輸入都基於行,並帶有std::getline 各條線然后可以標記化 ,如果需要,可以使用工具,如std::istringstreamstd::stoi 與通過std::cin的狀態標志相比,這使您可以以更簡單的方式對錯誤輸入進行錯誤處理。

例如,在下面的示例程序中,當您嘗試在第一行中輸入少於或多於4個整數時,或者如果不能將其中一個整數解析為整數,則將收到確切的錯誤消息。 重要的一點是,不是使用std::cin直接獲取整數值,而是首先接收完整的std::string行,然后將其拆分和分析。

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <stdexcept>
#include <exception>

// using just one of the many possible ways in C++ to tokenise a string:
std::vector<std::string> tokenise(std::string const& line)
{
    std::vector<std::string> tokens;
    std::istringstream is(line);
    std::string token;
    while (std::getline(is, token, ' '))
    {
        tokens.push_back(token);
    }

    return tokens;
}

std::vector<int> parse_four_integers(std::string const& line)
{
    auto const tokens = tokenise(line);

    if (tokens.size() != 4)
    {
        throw std::runtime_error("illegal token count: " + std::to_string(tokens.size()));
    }

    std::vector<int> result;
    for (auto&& token : tokens)
    {
        try
        {
            result.push_back(std::stoi(token));
        }
        catch (std::exception const&)
        {
            throw std::runtime_error("token " + token + " is not a valid integer");
        }
    }
    return result;
}

int main()
{
    try
    {
        std::string line;

        std::getline(std::cin, line);
        auto const four_integers = parse_four_integers(line);

        std::getline(std::cin, line);

        for (auto&& integer : four_integers)
        {
            std::cout << integer << "\n";
        }
        std::cout << line << "\n";
    }
    catch (std::exception const& exc)
    {
        std::cerr << exc.what() << "\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM