C++分割输入问题 [英] C++ Splitting the input problem

查看:37
本文介绍了C++分割输入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下形式的输入:

I am being given input in the form of:

(8,7,15)
(0,0,1) (0,3,2) (0,6,3)
(1,0,4) (1,1,5)
(2,1,6) (2,2,7) (2,5,8)
(3,0,9) (3,3,10) (3,4,11) (3,5,12)
(4,1,13) (4,4,14)
(7,6,15)

我必须记住三元组的数量.我编写了一个快速测试程序来尝试从 cin 读取输入,然后拆分字符串以从输入中获取数字.程序似乎没有读取所有的行,它在 (1,1,5) 之后停止,然后打印出一个随机的 7

where I have to remember the amount of triples there are. I wrote a quick testing program to try read the input from cin and then split string up to get the numbers out of the input. The program doesn't seem to read all the lines, it stops after (1,1,5) and prints out a random 7 afterwards

我为我试图为我的作业创建的功能之一创建了这个快速测试功能:

I created this quick testing function for one of the functions I am trying to create for my assignment:

int main ()
{
  string line;
  char * parse;

  while (getline(cin, line)) {

    char * writable = new char[line.size() + 1];
    copy (line.begin(), line.end(), writable);
    parse = strtok (writable," (,)");

    while (parse != NULL)
    {
      cout << parse << endl;
      parse = strtok (NULL," (,)");
      cout << parse << endl;
      parse = strtok (NULL," (,)");
      cout << parse << endl;
      parse = strtok (NULL," (,)");
    }

  }
  return 0;
}

有人可以帮我修复我的代码或给我一个工作示例吗?

Can someone help me fix my code or give me a working sample?

推荐答案

你可以使用这个简单的功能:

You can use this simple function:

istream& read3(int& a, int& b, int& c, istream& stream = cin) {
    stream.ignore(INT_MAX, '(');
    stream >> a;
    stream.ignore(INT_MAX, ',');
    stream >> b;
    stream.ignore(INT_MAX, ',');
    stream >> c;
    stream.ignore(INT_MAX, ')');

    return stream;
 }

它期望流从 ( 开始,所以它跳过任何字符并在它看到的第一个 ( 之后停止.它读入一个 int 到通过引用传递的 a 中(因此外部 a 受此影响)然后读取并跳过它看到的第一个逗号.清洗,冲洗, 重复.然后在读入第三个 int 后,它跳过结束的 ),因此准备再次执行.

It expects the stream to start at a (, so it skips any characters and stops after the first ( it sees. It reads in an int into a which is passed by reference (so the outside a is affected by this) and then reads up to and skips the first comma it sees. Wash, rinse, repeat. Then after reading the third int in, it skips the closing ), so it is ready to do it again.

它还返回一个 istream&,其中 operator bool 重载以在流结束时返回 false,这就是中断示例中的 while 循环.

It also returns an istream& which has operator bool overloaded to return false when the stream is at its end, which is what breaks the while loop in the example.

你像这样使用它:

// don't forget the appropriate headers...
#include <iostream>
#include <sstream>
#include <string>

int a, b, c;

while (read3(a, b, c)) {
    cout << a << ' ' << b << ' ' << c << endl;
}

打印:

8 7 15
0 0 1
0 3 2
0 6 3
1 0 4
1 1 5
2 1 6
2 2 7
2 5 8
3 0 9
3 3 10
3 4 11
3 5 12
4 1 13
4 4 14
7 6 15

当你给它你的输入时.

因为这是一个作业,我把它留给你添加错误处理等

Because this is an assignment, I leave it to you to add error handling, etc.

这篇关于C++分割输入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆