这是来自spoj的一个问题。与算法无关,只是c++。
样本输入
2
A aa bb cc def ghi
A bb c c c
样本输出
3.
5
它计算相同单词的最长序列http://www.spoj.pl/problems/WORDCNT/这个单词少于20个字符,但当我运行它时,它给出了分割错误。我使用eclipse对其进行了调试。这就是它崩溃的地方
if (strcmp(previous, current) == 0)
currentLength++;使用以下消息
"strcmp() at 0x2d0100“没有源代码,有什么问题吗?
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
int main(int argc, const char *argv[])
{
int t;
cin >> t;
while (t--) {
char line[20000], previous[21], current[21], *p;
int currentLength = 1, maxLength = 1;
if (cin.peek() == '\n') cin.get();
cin.getline(line, 20000);
p = strtok(line, " '\t''\r'");
strcpy(previous, p);
while (p != NULL) {
p = strtok(NULL, " '\t''\r'");
strcpy(current, p);
if (strcmp(previous, current) == 0)
currentLength++;
else
currentLength = 1;
if (currentLength > maxLength)
maxLength = currentLength;
}
cout << maxLength << endl;
}
return 0;
}发布于 2011-01-06 01:37:46
问题可能出在这里:
while (p != NULL) {
p = strtok(NULL, " '\t''\r'");
strcpy(current, p);而当进入循环时,p可以不为空。
当对其使用strcpy时,它可能为NULL。
更正确的循环形式应该是:
while ((p != NULL) && ((p = strtok(NULL, " \t\r")) != NULL))
{
strcpy(current, p);请注意。在C++中标记一个流要容易得多。
std::string token;
std::cin >> token; // Reads 1 white space seoporated word如果您想对行进行标记
// Step 1: read a single line in a safe way.
std::string line;
std::getline(std::cin, line);
// Turn that line into a stream.
std::stringstream linestream(line);
// Get 1 word at a time from the stream.
std::string token;
while(linestream >> token)
{
// Do STUFF
}发布于 2011-01-06 01:19:39
忘记在strtok上检查NULL,完成后将返回NULL,并且您不能在strcpy、strcmp等上使用该NULL。
请注意,您在strtok之后立即执行了strcpy,您应该在使用p作为源之前检查是否为null。
发布于 2011-01-06 01:40:53
strtok手册页上写着:
Each call to strtok() returns a pointer to a null-terminated string containing the next
token. This string does not include the delimiting character. If no more tokens are found,
strtok() returns NULL. 在你的代码中,
while (p != NULL) {
p = strtok(NULL, " '\t''\r'");
strcpy(current, p);一旦解析完整个字符串,您就不会检查NULL (对于p)。在此之后,您将尝试在current中复制p(现在为空),从而导致崩溃。
https://stackoverflow.com/questions/4606907
复制相似问题