读取整数行和带空格的字符串

Mar*_*jus 5 c++ string

我的输入格式如下:

整数多字串整数

我知道多字串的最大长度,但我不知道它包含多少字.我怎么读呢?

Ker*_* SB 5

我先读了这行,然后将第一个和最后一个单词转换为整数.松散:

std::string line;
std::getline(infile, line);

size_t ofs_front = line.find(' ');
size_t ofs_back = line.rfind(' ');

int front = std::strtol(line.substr(0, ofs_front).c_str(), NULL, 0);
int back  = std::strtol(line.substr(ofs_back).c_str(), NULL, 0);
std::string text = line.substr(ofs_front, ofs_back - ofs_front);
Run Code Online (Sandbox Code Playgroud)

你必须做一些修改来摆脱空间(例如增加偏移量以吞噬所有空间),你应该添加大量的错误检查.

如果要标准化文本中的所有内部空间,那么还有另一种使用字符串流的解决方案:

std::vector<std::string> tokens;
{
  std::istringstream iss(line);
  std::string token;
  while (iss >> token) tokens.push_back(token);
}
// process tokens.front() and tokens.back() for the integers, as above
std::string text = tokens[1];
for (std::size_t i = 2; i + 1 < tokens.size(); ++i) text += " " + tokens[i];
Run Code Online (Sandbox Code Playgroud)


per*_*eal 1

读取第一个整数。跳到字符串后面并跳过数字。然后从此时读取一个int。中间的部分是绳子。可能不是 100% 正确,但是:

char buf[256], *t = buf, *p, str[256];
fread(buf, 1, 256, file);
int s,e;
t += sscanf(buf, "%d", &s);
*p = buf + strlen(buf);
while (isdigit(*p)) p--;
sscanf(p, "%d", &e);
strncpy(str, p, p - t);
Run Code Online (Sandbox Code Playgroud)