簡體   English   中英

C++:如何輸入以逗號(,)分隔的值

[英]C++: how to input values separated by comma(,)

int a, b, c, d;

有4個變量。

我希望用戶輸入 4 個值,每個值用逗號 (,) 分隔

像這樣:

標准輸入:

1、2、3、4

以下代碼適用於 C

scanf("%d,%d,%d,%d", &a, &b, &c, &d);

但是我應該如何在 C++ 中編碼?

我對這里[1]的不正確評論感到有些驚訝。

您可以選擇兩條基本路線:

  • 使用操縱器樣式的對象處理分隔符,或
  • 為流注入需要空格以包含逗號的特殊方面。

我將專注於第一個; 即使是臨時性地(“共享”意味着您的代碼的其他部分也可以訪問它;本地字符串流將是充滿特殊行為的理想候選者),這通常是一個壞主意。

“下一項必須是逗號”提取器:

#include <cctype>
#include <iostream>

struct extract
{
  char c;
  extract( char c ): c(c) { }
};

std::istream& operator >> ( std::istream& ins, extract e )
{
  // Skip leading whitespace IFF user is not asking to extract a whitespace character
  if (!std::isspace( e.c )) ins >> std::ws;

  // Attempt to get the specific character
  if (ins.peek() == e.c) ins.get();

  // Failure works as always
  else ins.setstate( std::ios::failbit );

  return ins;
}

int main()
{
  int a, b;
  std::cin >> a >> extract(',') >> b;
  if (std::cin)
    std::cout << a << ',' << b << "\n";
  else
    std::cout << "quiznak.\n";
}

運行此代碼,僅當下一個非空白項是逗號時, extract操縱器/ extract器/任何東西才會成功。 否則會失敗。

您可以輕松修改它以使逗號可選:

std::istream& operator >> ( std::istream& ins, optional_extract e )
{
  // Skip leading whitespace IFF user is not asking to extract a whitespace character
  if (!std::isspace( e.c )) ins >> std::ws;

  // Attempt to get the specific character
  if (ins.peek() == e.c) ins.get();

  // There is no failure!
  return ins;
}

...

std::cin >> a >> optional_extract(',') >> b;

等等。

[1] cin >> a >> b; 等價於scanf( "%d,%d", ...); . C++ 不會神奇地忽略逗號。 就像在 C 中一樣,您必須明確地對待它們。

使用getline()stringstream的答案相同; 雖然組合有效,但實際問題只是從std::cin轉移到另一個流對象,並且仍然必須處理。

暫無
暫無

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

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