在 c++ 中的每个标记后添加空格

Add space after each token in c++

本文关键字:添加 空格 c++      更新时间:2023-10-16
#include<stdio.h>
#include<iostream>
#include<string.h>
int main()
{
char str[] = "01 21 03 06   0f 1a 1c 33   3a 3b";
char *pch;
char *m[100];
pch = strtok (str,"' ''  '");
size_t i = 0;
while (pch !=NULL)
{
m[i]=pch;
i++;
pch = strtok (NULL,"' ''  '");
}
for (int j=0;j!=i;j++)
{
 printf("%s",m[j]);
}
return 0;

我想在每个令牌后添加空格。我想将空间作为数组 m 的一部分包含在内。不是 printf(" ") 在我出来之前printf("%s",m[j]);放成"012103060f1a1c333a3b"如何在每 2 个字符后添加空格?

用 C++ 重写以使其更简单:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
  std::string str("01 21 03 06   0f 1a 1c 33   3a 3b");
  std::vector<std::string> m;
  std::istringstream inp(str);
  std::string token;
  while (inp >> token)
  {
    std::ostringstream outp;
    outp << token << " ";
    m.push_back(outp.str());
  }
  for (const auto& tok: m) { std::cout << tok; }
}

使用 stringstream 时,您只需读取由任何空格分隔的标记,并将它们以所需的格式流式传输到输出流。

请注意,使用输出流比此处真正需要的更通用。 它可以替换为m.push_back(token + " ");