C++分割输入问题
我得到的输入形式为:
(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
之后
我创建了这个快速测试函数我试图为我的作业创建的功能之一:
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;
}
有人可以帮助我修复我的代码或给我一个工作示例吗?
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)
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用这个简单的函数:
它期望流从
(
开始,因此它会跳过任何字符并在它看到的第一个(
之后停止。它读取 < code>int 到通过引用传递的a
中(因此外部a
受此影响),然后读取并跳过它看到的第一个逗号然后清洗、冲洗,读完第三个。int
中,它会跳过关闭的)
,因此它还准备好再次执行此操作,它还返回一个包含
的
重载返回istream&
。当流结束时,操作符 boolfalse
,这就是破坏示例中的while
循环的:
原因 打印:
当你给它你的输入时,
因为这是一项作业,我。让您添加错误处理等。
You can use this simple function:
It expects the stream to start at a
(
, so it skips any characters and stops after the first(
it sees. It reads in anint
intoa
which is passed by reference (so the outsidea
is affected by this) and then reads up to and skips the first comma it sees. Wash, rinse, repeat. Then after reading the thirdint
in, it skips the closing)
, so it is ready to do it again.It also returns an
istream&
which hasoperator bool
overloaded to returnfalse
when the stream is at its end, which is what breaks thewhile
loop in the example.You use it like this:
That prints:
When you give it your input.
Because this is an assignment, I leave it to you to add error handling, etc.
我在 9 天前写了一篇博客来解析这些输入:
您可以在此处查看输入的输出:http://ideone.com/qr4DA
I've written a blog 9 days back exactly to parse such inputs:
And you can see the output here for your input : http://ideone.com/qr4DA