【发布时间】:2015-08-20 14:17:04
【问题描述】:
我的代码在我的计算机上的 codeblocks 编译器上运行良好,但是当我将它上传到在线编辑器时,我收到 Segmentation fault 错误,我不知道为什么。
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main(int argc, char *argv[]) {
ifstream stream(argv[1]);
char line[1000];
int x,last=-1;
while (stream>>line)
{
x = atoi(strtok(line,","));
cout<<x;
last=x;
while(x=atoi(strtok(NULL,",")))
{
if(x!=last)
{
cout<<","<<x;
last=x;
}
}
cout<<endl;
}
return 0;
}
您会得到一个排序后的数字列表,其中包含重复的数字。打印出已删除重复项的排序列表。
这是输入
6,7,8,9,9,10,11,12,13,14,15
11,12,13,14,15,16,17,18,19,20
2,2,2,2,2
10,11,12,13,14,15,16,16,17
13,14,14,15,16,17,17,17,18
15,16,17,17,18,18,18,18,19,19,20
2,3,4,5,5
13,14,15,16,17
10,11,12,13,14,15,15,15,15,16,16,16
12,13,14,15,16,17,17,18
5,6,7,8,9,10,11
14,14,14,15,15,16,17,17,18,19,19,20,21,22
13,14,15,16,16,17,17,18
15,16,17,18,19,20,21,21,21,21,22,22
6,6,6,7,8,9,10,11,11,11,12,12,13
12,12,13,14,15,15,16,17,17,18,19,19,20,21
8,9,9,9,10,10,11,12,13,13,14,15
12,13,14,15,16,17,18
1,1,1,2,2,3,3,4,4
1,2,3,4
【问题讨论】:
-
什么“在线编辑器”?你给我们留下的只是猜测。
-
顺便说一句,如果该代码应该一次读取一行,那么您做错了。而且我不知道您为什么使用 C 数组进行字符串存储。或用于字符串操作的 C 函数。你也没有正确地做
strtok(你在哪里检查最终令牌???)。事实上,我越看这个,它就越错误。 -
我不知道这条线想要做什么:
while(x=atoi(strtok(NULL,",")))。你为什么在NULL上打电话给strtok?另外,赋值运算符是否应该是==? -
@Carlton NULL 到
strtok很好。 NULL 到atoi是可疑的。 -
@Carlton,是的,在 first 调用时不行,但 OP 没有这样做。