【问题标题】:How to read a string separated by spaces in C++? [closed]如何在 C++ 中读取由空格分隔的字符串? [关闭]
【发布时间】:2014-02-21 16:20:03
【问题描述】:

用户引入了一个像“1 10 4 1 53”这样的字符串,我必须读取字符串中的所有数字。我怎样才能在 C++ 中做到这一点?

【问题讨论】:

  • 这个问题和类似的问题已经在这里讨论过无数次了;你试过搜索吗?
  • 关键字是“StackOverflow C++ 读取文件整数空格分隔”

标签: c++ string


【解决方案1】:

如果您不关心速度,请使用stringstream

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int
main()
{
  string str("1 10 4 1 53");
  stringstream ss(str);
  int n;
  while (ss >> n)
    cout << n << endl;
  return 0;
}

【讨论】:

    【解决方案2】:

    只需将其放入istringstream 并使用普通的&gt;&gt;

    【讨论】:

      【解决方案3】:

      您可以将输入作为字符串,然后您可以使用strtok() 对字符串进行标记以分隔字符串。

      【讨论】:

      • 1980 调用;他们希望恢复他们的字符串标记化技术......(那是 三十四 年前!!)
      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 2016-08-05
      • 2014-09-28
      • 1970-01-01
      相关资源
      最近更新 更多